If Dict Contains a particular key

Alex Martelli aleax at mac.com
Thu Apr 26 01:47:03 EDT 2007


mensanator at aol.com <mensanator at aol.com> wrote:
   ...
> >      if 'a' in thedict:
> >          ...
> >
> > There's no need for the call to keys().
> 
> Why not
> 
> if thedict.has_key('a'):
>     pass
> elde:
>     pass

has_key exists only for backwards compatibility; the 'in' operator is
preferable.

$ python -mtimeit -s'd={}' 'd.has_key(23)'
1000000 loops, best of 3: 0.289 usec per loop
$ python -mtimeit -s'd={}' '23 in d'      
10000000 loops, best of 3: 0.139 usec per loop

Why consume twice as much time with no advantages whatever?!


Alex



More information about the Python-list mailing list