[Python-Dev] Proposal: defaultdict

Nick Coghlan ncoghlan at gmail.com
Sat Feb 18 04:43:42 CET 2006

Guido van Rossum wrote:
> But there were
> several suggestions that this would be fine functionality to add to
> the standard dict type -- and then I really don't see any other way to
> do this.

Given the constructor problem, and the issue with "this function expects a 
plain dictionary", I think your original instinct to use a subclass may have 
been correct.

The constructor is much cleaner that way:

# bag like behavior
dd = collections.autodict(int)
for elem in collection:
      dd[elem] += 1

# setdefault-like behavior
dd = collections.autodict(list)
for page_number, page in enumerate(book):
      for word in page.split():

And it can be a simple fact that for an autodict, "if key in d" and "d[key]" 
may give different answers.

Much cleaner than making the semantics of normal dicts dependent on:
  a. whether or not on_missing has been overridden
  b. whether or not default_factory has been set


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-Dev mailing list