dictionary: sorting the values preserving the order

Satchidanand Haridas sharidas at zeomega.com
Fri Apr 1 03:25:38 EST 2005


Rakesh wrote:

>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
>
>  
>
the following code does that:
 >>> d1 = {'a':4,'b':5,'c':1,'d':2,'e':3}
 >>> i1 = [ (d1[i], i) for i in d1.keys() ]
 >>> i1.sort()
 >>> i1
[(1, 'c'), (2, 'd'), (3, 'e'), (4, 'a'), (5, 'b')]
 >>> for each in i1:
...     print each[1]  
c
d
e
a
b


thanks,
Satchit




>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