[Python-Dev] Proposal: defaultdict

Jack Diederich jack at performancedrivers.com
Fri Feb 17 17:19:32 CET 2006

On Thu, Feb 16, 2006 at 01:11:49PM -0800, Guido van Rossum wrote:
> Google has an internal data type called a DefaultDict which gets
> passed a default value upon construction. Its __getitem__ method,
> instead of raising KeyError, inserts a shallow copy (!) of the given
> default value into the dict when the value is not found. So the above
> code, after
>   d = DefaultDict([])
> can be written as simply
>   d[key].append(value)
> Note that of all the possible semantics for __getitem__ that could
> have produced similar results (e.g. not inserting the default in the
> underlying dict, or not copying the default value), the chosen
> semantics are the only ones that makes this example work.

Having __getitem__ insert the returned default value allows it to
work with a larger variety of classes.  My own ForgivingDict does not
do this and works fine for ints and lists but not much else.

fd = ForgivingDict(list)
fd[key] += [val] # extends the list and does a __setitem__

The += operator isn't useful for dicts.

How can you make a defaultdict with a defaultdict as the default?
My head asploded when I tried it with the constructor arg.
It does seem possible with the 'd.default = func' syntax

# empty defaultdict constructor
d = defaultdict()
d.default = d
tree = defaultdict()
tree.default = d.copy


More information about the Python-Dev mailing list