[Python-Dev] collections module (original) (raw)

Robert Brewer fumanchu at amor.org
Sat Jan 10 14:37:46 EST 2004


Raymond H. quoted Martin L. thusly:

> Both applications could be implemented if dictionaries had > the notion of a default value, which would be generated > by a callable (whether with or without argument is debatable) > > # count things > d = {} > d.defaultmaker = lambda k:0 > for t in things: > d[t] += 1 > > # sort things by category > d = {} > d.defaultmaker = lambda k:[] > for t in things: > d[category(t)].append(t)

Then answered with:

These both read cleanly.

I really like this idea as a general purpose solution with broad applicability. It fully encapsulates the ideas behind bag construction and building dicts of lists. Instead of a method, it may be better to use a keyword argument in the constructor: d = dict(default = lambda k:[]) for t in things: d[category(t)].append(t) If lambda is made parameterless, it allows type constructors to be used for the most common cases: dict(default=list) # this is clear enough dict(default=int) # this may be too cute

This seems a bit too easy to do "as needed" to warrant a new builtin, but that's why we have proposals, I guess:

class DefaultingDict(dict):

def __init__(self, default):
    self.default = default

def __getitem__(self, key):
    return self.get(key, self.default())

d = DefaultingDict(lambda: 0) d.update({'a': 1, 'b': 2, 'c': 3}) d {'a': 1, 'c': 3, 'b': 2} for x in ['a', 'b', 'c', 'd']: ... d[x] += 1 ... d {'a': 2, 'c': 4, 'b': 3, 'd': 1}

Robert Brewer MIS Amor Ministries fumanchu at amor.org



More information about the Python-Dev mailing list