Pythonic way for missing dict keys

Carsten Haese carsten at uniqsys.com
Fri Jul 20 22:41:46 CEST 2007


On Fri, 2007-07-20 at 19:39 +0000, Alex Popescu wrote:
> Neil Cerutti <horpner at yahoo.com> wrote in 
> news:slrnfa2325.n4.horpner at FIAD06.norwich.edu:
> 
> > On 2007-07-20, Alex Popescu <the.mindstorm.mailinglist at gmail.com> wrote:
> >> Hi all!
> >>
> >> I am pretty sure this has been asked a couple of times, but I
> >> don't seem to find it on the archives (Google seems to have a
> >> couple of problems lately).
> >>
> >> I am wondering what is the most pythonic way of dealing with missing 
> >> keys and default values.
> >>
> >> According to my readings one can take the following approaches:
> > 
> > There's also the popular collections.defaultdict. 
> > 
> > Usually, the get method of normal dicts is what I want. I use a
> > defaultdict only when the implicit addition to the dictionary of
> > defaulted elements is what I really want.
> > 
> 
> This looks like the closest to my needs, but in my case the default value 
> involves the creation of a custom object instance that is taking parameters 
> from the current execution context, so I am not very sure I can use it.

If by "current execution context" you mean globally visible names, this
should still be possible:

>>> from collections import defaultdict
>>> def make_default():
...    return x+y
... 
>>> dd = defaultdict(make_default)
>>> x = 40
>>> y = 2
>>> print dd[0]
42
>>> x = "Dead"
>>> y = " Parrot"
>>> print dd[1]
Dead Parrot
>>> print dd
defaultdict(<function make_default at 0xb7f71e2c>, {0: 42, 1: 'Dead Parrot'})

HTH,

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





More information about the Python-list mailing list