Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 979
zephyr Avatar asked Oct 26 '25 15:10

zephyr


1 Answers

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.

like image 165
Azar Avatar answered Oct 29 '25 06:10

Azar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!