Pythonic way for missing dict keys

Carsten Haese carsten at uniqsys.com
Fri Jul 20 22:38:21 CEST 2007


On Fri, 2007-07-20 at 20:10 +0000, Alex Popescu wrote:
> Carsten Haese <carsten at uniqsys.com> wrote in
> news:1184959878.3586.18.camel at dot.uniqsys.com: 
> 
> > On Fri, 2007-07-20 at 19:08 +0000, Alex Popescu wrote:
> >> Hi all!
> >> 
> 
> >
> > [snip...]
> >
> > 
> > This is called "Look before you leap." Note that "if key in my_dict"
> > is preferred over has_key().
> >
> 
> Can you please detail why in is prefered over has_key? Is it about 
> readability/performance?

Yes, it's about both readability and performance:

[carsten at dot ~]$ python -m timeit -s "a={}" "a.has_key('foo')"
1000000 loops, best of 3: 0.601 usec per loop
[carsten at dot ~]$ python -m timeit -s "a={}" "'foo' in a"
1000000 loops, best of 3: 0.307 usec per loop

> Unfortunately, the get(key, None) suggestion is not 100% equivalent to 
> my posted code, and once I add the addition of the new object to the map 
> I think 1/ and 3/ are equivalent (if no other 
> readability/performance/etc is involved).

Indeed, I missed that in 1/ and 2/ you're also adding the value to the
dictionary. You could use setdefault instead of get:

my_obj = my_dict.setdefault(key, myobject())

But if you want to defer creation of the default value until it's
actually needed, you're better off with the "Look before you leap"
approach.

-- 
Carsten Haese
http://informixdb.sourceforge.net





More information about the Python-list mailing list