Python Forum
Some doubts on dictionaries - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Some doubts on dictionaries (/thread-21837.html)



Some doubts on dictionaries - newbieAuggie2019 - Oct-16-2019

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,


RE: Some doubts on dictionaries - stullis - Oct-17-2019

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.


RE: Some doubts on dictionaries - perfringo - Oct-17-2019

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)