counting occurrences
Grant Griffin
not.this at seebelow.org
Fri Aug 3 16:47:34 EDT 2001
Hi Gang,
I have long used dictionaries to counting occurrences of something (usually
strings). It goes something like this:
counter = {}
for s in strings:
counter[s] = counter.get(s, 0) + 1
(I used to use "has_key" until I caught on to "get".)
This then usually leads to a need to "sort keys by value"--something like this:
itemlist = [(value, key) for (key, value) in counter.items()]
itemlist.sort()
itemlist.reverse()
(Which demonstrates yet _another_ valuable use for list comprehensions<wink>.)
Then, "itemlist" contains sorted (value, key) pairs--usually to be printed or
something.
For me, this sort of thing comes up so often that it qualifies as an "idiom".
However, the sorting thing is a pain (at least a first--then you get so you like
to impress people by having finally found a use for list comprehensions<wink>),
so I mentioned to a friend that it would sure be nice if Python dictionaries had
an "items_sorted_by_value" method. But, among other things, my friend (who has
been using Python for a *long* time) said that he has never wanted such a thing,
because he doesn't see counting occurrences "as a dictionary operation".
So how do you think he does it?
tim:-help-me-out-here<wink>-ly y'rs,
=g2
_____________________________________________________________________
Grant R. Griffin g2 at dspguru.com
Publisher of dspGuru http://www.dspguru.com
Iowegian International Corporation http://www.iowegian.com
More information about the Python-list
mailing list