counting occurrences

Grant Griffin not.this at seebelow.org
Mon Aug 6 16:51:40 CEST 2001


In article <mailman.996902347.22149.python-list at python.org>, "Tim says...
>
>[Grant Griffin]
>> I have long used dictionaries to counting occurrences of
>> something (usually strings).  It goes something like this:
>> ...
>> For me, this sort of thing comes up so often that it qualifies as
>> an "idiom".
>> ...
>> However, the sorting thing is a pain ...
>> so I mentioned to a friend that it would sure be nice if Python
>> dictionaries had an "items_sorted_by_value" method.

>Won't happen -- you can easily write a function for it yourself in Python,
>and it's not going to run significantly faster if it's coded by us in C
>instead.  Dicts have no internal ordering, so the best efficient thing
>anyone can do here is materialize a list in full, sort it, and pull it apart
>again.

I guess I wasn't really after "speed".  I was more interested in making this
common operation more _accessible_ to beginners, and more _convenient_ to
all--you know, kindda like list comprehensions.  (Or do we have LCs purely for
"speed"<wink>?)

>Note that in Python 2.2, you can *subclass* from dicts, like here in
>grantdict.py:
>
>class Grant(dictionary):
>    def items_by_value_backwards(self):
>        items = [(v, k) for k, v in self.items()]
>        items.sort()
>        items.reverse()
>        return [(k, v) for v, k in items]

Great--thanks!  (Anything that uses _two_ list comprehensions in five lines
can't be _all_ bad <wink>.)

>...
>Well, no sane person wants it built in <wink>, but of course dicts are
>natural for this.

OK, maybe you're right: maybe it isn't a good idea to have it built in...

watch-sourceforge-for-my-submission-of-'grantdict.py'-as-part
   -of-the-2.3-standard-library-<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