sorting dictionaries by value
Thomas Guettler
pan-newsreader at thomas-guettler.de
Wed Jan 29 12:11:25 EST 2003
On Wed, 29 Jan 2003 09:39:52 +0100, Hilbert 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"
Hi Hilbert,
I would do it like this:
d={"one" : { "red" : 23, "blue" : 99 },
"two" : { "red" : 43, "blue" : 17 },
"three" : { "red" : 34, "blue" : 65 },
"four" : { "red" : 36, "blue" : 38 }
}
blue_list=[]
for key, value in d.items():
blue_list.append([value["blue"], key])
def blue_cmp(a, b):
return cmp(a[0], b[0])
blue_list.sort(blue_cmp)
print blue_list
# --> [[17, 'two'], [38, 'four'], [65, 'three'], [99, 'one']]
--
Thomas Guettler <guettli at thomas-guettler.de>
http://www.thomas-guettler.de
More information about the Python-list
mailing list