[Python-Dev] tally (and other accumulators)

Jeremy Hylton jeremy at alum.mit.edu
Tue Apr 4 17:01:05 CEST 2006


On 4/4/06, Alex Martelli <aleaxit at gmail.com> wrote:
> import collections
> def tally(seq):
>      d = collections.defaultdict(int)
>      for item in seq:
>          d[item] += 1
>      return dict(d)
>
> Nevertheless, simplicity and generality make it advisable to supply
> it as part of the standard library (location TBD).
>
> A good alternative would be a classmethod tally within
> collections.defaultdict, building and returning a defaultdict as
> above (with a .factory left to int, for further possible use as a
> 'bag'/multiset data structure); this would solve the problem of where
> to locate tally if it were to be a function.  defaultdict.tally would
> be logically quite similar to dict.fromkeys, except that keys
> happening repeatedly get counted (and so each associated to a value
> of 1 and upwards) rather than "collapsed".

Putting it somewhere in collections seems like a great idea. 
defaultdict is a bit odd, because the functionality doesn't have
anything to do with defaults, just dicts.  maybe a classmethod on
regular dicts would make more sense?

I write this function regularly, so I'd be happy to have it available directly.

Jeremy


More information about the Python-Dev mailing list