sorting dictionaries by value

Klaus Alexander Seistrup spam at magnetic-ink.dk
Wed Jan 29 03:56:25 EST 2003


Hilbert wrote:

> 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"

#v+
>>> res = []
>>> for key in dict.keys():
...     res.append( (dict[key]['blue'], key) )
... 
>>> res.sort()
>>> for (val, key) in res:
...     print '%d "%s"' % (val, key)
... 
17 "two"
38 "four"
65 "three"
99 "one"
>>> 
#v-

('Tis prudent to use another word than "dict" to label a dictionary.)


  // Klaus

-- 
 ><> 	vandag, môre, altyd saam




More information about the Python-list mailing list