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
i.e. sorting by dictionary values and for equal values first one comes first(i.e 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With