[Python-ideas] Testing Key-Value Membership In Dictionaries
Jacob Holm
jh at improva.dk
Sun Oct 9 23:21:21 CEST 2011
Hi
On 2011-10-09 22:25, Karthick Sankarachary wrote:
> Currently, to check whether a single key is in a dictionary, we use the "in"
> keyword. However, there is no built-in support for checking if a key-value
> pair belongs in a dictionary.
Yes there is. You use the "viewitems()" method in 2.7 or the "items()"
method in 3.x to get a set-like view on the dictionary, then test
membership of that.
So for your example:
>>> tel = {'jack': 4098, 'sape': 4139}
>>> ('jack', 4098) in tel.items() # use viewitems() in 2.7
True
>>> ('jack', 4000) in tel.items() # use viewitems() in 2.7
False
>>> 'jack' in tel
True
The above code *works* in all versions of python (AFAIK), but for large
dictionaries it can be quite inefficient in all versions before 3.0.
>From 3.0 forward this is the "one obvious way to do it", and is fast no
matter the size of the dictionary (expected O(1) time).
HTH
- Jacob
More information about the Python-ideas
mailing list