Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Some doubts on dictionaries
#1
Hi!

I thought that checking if a certain 'x' element existed in a certain dictionary named, let's say 'mixedBag' would check if that 'x' element is in that dictionary, being either a 'key', either a 'value' in it, but it seems that it is not the case.

I'll explain my doubt with an example in IDLE:
Output:
>>> famousActors = {'Clint Eastwood': 89, 'Robert Redford': 83, 'Sigourney Weaver': 70, 'Glenn Close': 72} >>> 'Clint Eastwood' in famousActors True >>> 'Clint Eastwood' in famousActors.keys() True >>> 'Clint Eastwood' in famousActors.values() False >>> 89 in famousActors False >>> 89 in famousActors.keys() False >>> 89 in famousActors.values() True >>>
Where you can see, that if I check for 'Clint Eastwood' in the dictionary famousActors, or for 'Clint Eastwood' in the keys of the dictionary famousActors, both return the Boolean value of True (as I expected), but when I check for 89 in the dictionary famousActors, it returns the Boolean value of False (something that I was not expecting at all).

Am I missing something? Because I can see clearly that 89 is indeed in the dictionary famousActors, something that is later corroborated when I check for 89 in the values of the dictionary famousActors, returning the Boolean value of True (as I expected).

Thanks and all the best,
newbieAuggie2019

"That's been one of my mantras - focus and simplicity. Simple can be harder than complex: You have to work hard to get your thinking clean to make it simple. But it's worth it in the end because once you get there, you can move mountains."
Steve Jobs
Reply
#2
There has been a misunderstanding. When checking for "x" in a dictionary, the standard operation is to check for keys. That's true in every language I've studied. Dictionaries (or maps in other languages) are optimized for value retrieval by key and so cannot be queried by value. Even using dict.values() loops over the keys in the dictionary and returns the value for each one.
Reply
#3
I suggest to watch Raymond Hettinger famous Transforming Code into Beautiful, Idiomatic Python.

There is part named Dictionary Skills which should be mandatory to every pythonista (includes explanation why didn't you find dictionary values you were expecting). NB! In current versions you can't do del-trick he showed (you will get RuntimeError: dictionary changed size during iteration, reason being that d.keys() now returns view)
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020