[Python-ideas] Testing Key-Value Membership In Dictionaries

John O'Connor jxo6948 at rit.edu
Sun Oct 9 22:54:16 CEST 2011


You can do the same check using a default argument in dict.get such as...

>>> tel.get('jack', None) == 4098
True
>>> tel.get('jack', None) == 4000
False
>>> tel.get('jill', None) == 4000
False


- John



On Sun, Oct 9, 2011 at 4:25 PM, Karthick Sankarachary <
karthick.sankarachary at gmail.com> wrote:
> Hello Python Ideas,
>
> 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.
>
> Currently, we presuppose that the object being checked has the same type
as
> that of the key. What if we allowed the "in" operator to accept a tuple
that
> denotes a (mapped) key-value pair?
>
> Let us consider how that might work using the canonical example given in
the
> tutorial:
>
>>>> tel = {'jack': 4098, 'sape': 4139}
>
>
>>>> ('jack', 4098) in tel
> True
>>>> ('jack', 4000) in tel
> False
>>>> 'jack' in tel
> True
>
> As you can see, the "in" operator would interpret the object as either a
key
> or a key-value pair depending on the actual types of the object, key and
> value. In the key itself happens to be a tuple, then the key-value
> membership test would involve a nested tuple, whose first item is a tuple
> denoting the key.
>
> Best Regards,
> Karthick Sankarachary
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20111009/35e18cf7/attachment.html>


More information about the Python-ideas mailing list