[Python-Dev] Proposal: defaultdict

Raymond Hettinger python at rcn.com
Fri Feb 17 05:27:17 CET 2006

>> Over lunch with Alex Martelli, he proposed that a subclass of dict
>> with this behavior (but implemented in C) would be a good addition to
>> the language

I would like to add something like this to the collections module, but a PEP is 
probably needed to deal with issues like:

* implications of a __getitem__ succeeding while get(value, x) returns x 
(possibly different from the overall default)
* implications of a __getitem__ succeeding while __contains__ would fail
* whether to add this to the collections module (I would say yes)
* whether to allow default functions as well as default values (so you could 
instantiate a new default list)
* comparing all the existing recipes and third-party modules that have already 
done this
* evaluating its fitness for common use cases (i.e. bags and dict of lists).
* lay out a few examples:

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

# setdefault-like behavior
dd = collections.default_dict()
dd.default(list)                                # instantiate a new list for 
empty cells
for page_number, page in enumerate(book):
    for word in page.split():


More information about the Python-Dev mailing list