user40647 user40647 - 5 months ago 6
Python Question

search efficiently in a dictionary

I have a long dictionary of form string to string like

{'a':'b' , 'c':'d'}


I want to efficiently search for a key so that I can get the corresponding answer from the dictionary, but I would like a better search than just iterating over the entire dictionary. Is there a better way like storing in a set so that I can search efficiently. I looked at sets, but I could only find ways to store individual string, but not dictionary elements.

Answer

If you have a dictionary d and want to test for membership of a key k, you can just use k in d or k not in d. For example:

>>> d = {'a':'b' , 'c':'d'}
>>> 'a' in d
True
>>> 'x' in d
False
>>> 'a' not in d
False
>>> 'x' not in d
True
>>>

These checks should be very efficient since dictionaries (and sets) are implemented with hash tables.

Comments