user40647 user40647 - 4 months ago 5x
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.


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
>>> 'x' in d
>>> 'a' not in d
>>> 'x' not in d

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