[Python-Dev] PEP 265 - Sorting dicts by value

Nick Coghlan ncoghlan at iinet.net.au
Mon Sep 13 06:46:53 CEST 2004


David Harrison wrote:
> Hi all,
> 
> Quick pep265 summary : People frequently want to count the occurrences
> of values in a dict, or sort the results of a d.items() call by value.
>  This could be done by extending the current items() definition, or by
> creating a new function for the dict object (both requiring a C
> implementation).

In Python 2.4:

->>> ud = dict(a=1, b=2, c=3)
->>> from operator import itemgetter
->>> print sorted(ud.items(), key=itemgetter(1), reverse=True)
[('c', 3), ('b', 2), ('a', 1)]


I'm not entirely sure who needs to be thanked for this addition, but it 
sure makes the 'decorate-sort-undecorate' idiom very, very easy to 
follow (which was, in fact, the point - I do remember that much of the 
discussion).

I think the addition of 'sorted', and the keyword arguments for both it 
and list.sort make PEP 265 somewhat redundant.

Cheers,
Nick.


More information about the Python-Dev mailing list