sorting dictionaries by value

Uwe Schmitt uwe.schmitt at procoders.net
Wed Jan 29 04:59:46 EST 2003


Hilbert <hilbert at microsoft.com> wrote:
> Hello,

> I have the following dictionary:

>>>> dict = {
> ... "one" : { "red" : 23, "blue" : 99 },
> ... "two" : { "red" : 43, "blue" : 17 },
> ... "three" : { "red" : 34, "blue" : 65 },
> ... "four" : { "red" : 36, "blue" : 38 } }

> I'd like to print the value of  "blue" sorted and the corresponding key of
> dict, like:

> 17 "two"
> 38 "four"
> 65 "three"
> 99 "one"

*Never* name a dictionary 'dict', this is a builtin class,
representing the dictionary data type.

One solution:

Decorate-Sort-Undecorate:

d = { 'one' : ... } 

li =[ (v["blue"],k) for k,v in d.items() ]
li.sort()
result = [ (k,v) for v,k in li ]

I did not test this code, hope it works.

Greetings, Uwe.


-- 
Dr. rer. nat. Uwe Schmitt      Computer science is no more about Computers,
uwe.schmitt at num.uni-sb.de      than astronomy is about telescopes. (Dijkstra)
http://www.procoders.net           




More information about the Python-list mailing list