dict.setdefault()

Raymond Hettinger python at rcn.com
Tue Apr 12 00:49:21 CEST 2011


On Apr 11, 2:35 pm, rantingrick <rantingr... at gmail.com> wrote:
> setdefault should take **kw args in the case of needing to set
> multiple defaults at one time. I would even settle for an *arg list if
> i had to. Anything is better than...
>
> d.setdefault(blah, blah)
> d.setdefault(blah, blah)
> d.setdefault(blah, blah)
> d.setdefault(blah, blah)
> if blah is not blah:
>     d.setdefault(blah, blah)

I hate to feed a troll, but I'm curious when you see that pattern of
calls.  The typical use case always makes immediate use of the value
returned by setdefault():

   d.setdefault(key, []).append()

The pattern you've shown would more typically be expressed like this:

   for key in multiple_defaults.items():
       if key, default_value not in d:
           d[key] = default_value

Or people sometimes use updates to get the same effect:

   result = multiple_defaults.copy()
   result.update(d)

Another approach is to use something like ChainMap() which has been
added to Python 3.3. http://docs.python.org/dev/library/collections.html#collections.ChainMap

   result = ChainMap(d, multiple_defaults)


Raymond



More information about the Python-list mailing list