user40647 user40647 - 1 year ago 53
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 Source

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.