简体   繁体   中英

Sort a dictionary in python by values but maintaining the key order for equal values

Lets say there is a dictionary

d = {"P1":77,"P2":89,"P3":77}

I want to print the results in following form

P2: 89

P1: 77

P3: 77

ie sorting by dictionary values and for equal values first one comes first(ie P1 comes before P3)

I did the following

import collections
od = collections.OrderedDict(sorted(d.items(), key=lambda x:x[1], reverse=True))

od gives

OrderedDict([('P2', 89), ('P3', 77), ('P1', 77)])

How can I get P1 before P3 ?

Do this:

od = collections.OrderedDict(sorted(d.items(), key = lambda x:(-x[1],x[0])))

As @Padraic said, "You cannot sort from highest to lowest and lowest to highest." Therefore, you have to trick the sorted function by making it see the highest numbers as the lowest ones. It is sub-sorted by the natural order of the keys.

Python's sort is a stable sort, meaning items stay in their original order if they compare equal. If you start with an OrderedDict and just sort on the value only, they keys will stay in their original order. In your case, however, sort them with a key that that sorts highest to lowest directly, instead of reversing the sort, to keep them in the same key order.

Example

from collections import OrderedDict
d = OrderedDict([('P1',77),('P2',89),('P3',77)])
print sorted(d.items(),key=lambda x:-x[1])
d = OrderedDict([('P3',77),('P2',89),('P1',77)])
print sorted(d.items(),key=lambda x:-x[1])

Output

[('P2', 89), ('P1', 77), ('P3', 77)]
[('P2', 89), ('P3', 77), ('P1', 77)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM