If Dict Contains a particular key

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Thu Apr 26 03:06:53 EDT 2007


In <1177565430.992904.149450 at n35g2000prd.googlegroups.com>,
mensanator at aol.com wrote:

> On Apr 24, 1:41 pm, Steven Bethard <steven.beth... at gmail.com> wrote:
>> Steven Howe wrote:
>>
>> > or try:
>> > thedict = { 'a': 1, 'b':2, 'c':3 }
>> > if 'a' in thedict.keys():
>> >    print thedict['a']
>>
>> Better yet, just:
>>
>>      if 'a' in thedict:
>>          ...
>>
>> There's no need for the call to keys().
> 
> Why not
> 
> if thedict.has_key('a'):
>     pass
> elde:
>     pass

Additional to the speed argument, the ``in`` operator works with more
types, like lists, sets and "iterables".  And if someone implements a
"container" class with membership testing, it is more likely he writes a
`__contains__()` method than a `has_key()` method.

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list