Pre-PEP: Dictionary accumulator methods

Roose b at b.b
Sun Mar 20 13:46:59 EST 2005


> Another option with no storage overhead which goes part way to reducing
> the awkwardness would be to provide a decorator class accessible through
> dict. The decorator class would take a value or function to be used as
> the default, but apart from __getitem__ would simply forward all other
> methods through to the underlying dictionary.

I'm not sure I like the decorator -- I would never use that flexibility to
have more than one default.  I can't come up with any reason to ever use
that.

I think it works best as a simple subclass:

class DefaultDict(dict):

  def __init__(self, default, *args, **kwargs):
    dict.__init__(self, *args, **kwargs)
    self.default = default

  def __getitem__(self, key):
    return self.setdefault(key, copy.copy(self.default))

d = DefaultDict(0)
for x in [1, 3, 1, 2, 2, 3, 3, 3, 3]:
  d[x] += 1
pprint(d)

d = DefaultDict([])
for i, x in enumerate([1, 3, 1, 2, 2, 3, 3, 3, 3]):
  d[x].append(i)
pprint(d)

Output:

{1: 2, 2: 2, 3: 5}
{1: [0, 2], 2: [3, 4], 3: [1, 5, 6, 7, 8]}





More information about the Python-list mailing list