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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4