dictionary: sorting the values preserving the order

Rakesh rakesh_usenet at yahoo.com
Fri Apr 1 01:40:53 EST 2005


Hi,
  For a particular problem of mine, I want to sort <key, value> pairs
by its value.

Eg:

Input:

A, 4
B, 5
C, 1
D, 2
E, 3

I would like the output to be:

C
D
E
A
B

i.e. I would like to get the keys in the sorted order of values.

I did google around a little bit. One solution to a similar problem
suggested is:

# Courtesy:
http://aspn.activestate.com/ASPN/Python/Cookbook/Recipe/52306
def sortedDictValues3(adict):
    keys = adict.keys()
    keys.sort()
    return map(adict.get, keys)

This gets a list sorted by the keys. How would I get a revised
dictionary 
sorted by its values.




More information about the Python-list mailing list