dict.has_key(x) versus 'x in dict'

Duncan Booth duncan.booth at invalid.invalid
Wed Dec 6 12:45:10 EST 2006


Paul Melis <paul at floorball-flamingos.nl> wrote:

>> Ah, thx. Thought the "x in d" syntax might search in d.values() too.
> 
> I don't think it does
> 
> Python 2.4.3 (#1, Nov 19 2006, 13:16:36)
> [GCC 3.4.5 (Gentoo 3.4.5-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> d={1:'a',2:'b'}
>>>> 1 in d
> True
>>>> 'a' in d
> False
> 
It is easy enough to to check if you remember that 'in' maps to the 
__contains__ method:

>>> help({}.__contains__)
Help on built-in function __contains__:

__contains__(...)
    D.__contains__(k) -> True if D has a key k, else False



More information about the Python-list mailing list