Pre-PEP: Dictionary accumulator methods

Evan Simpson evan at tokenexchange.com
Mon Mar 21 18:39:20 EST 2005


Raymond Hettinger wrote:
> I would like to get everyone's thoughts on two new dictionary methods:
> 
>         def count(self, value, qty=1):
> 
>         def appendlist(self, key, *values):

-1.0

When I need these, I just use subtype recipes.  They seem way too 
special-purpose for the base dict type.

class Counter(dict):
     def __iadd__(self, other):
         if other in self:
             self[other] += 1
         else:
             self[other] = 1
         return self

c = Counter()
for item in items:
     c += item

class Collector(dict):
     def add(self, key, value):
         if key in self:
             self[key].append(value)
         else:
             self[key] = [value]

c = Collector()
for k,v in items:
     c.add(k, v)

Cheers,

Evan @ 4-am




More information about the Python-list mailing list