i want to sort all dictionary in increasing but whenever i get same values sort them in decreasing order

Viewed 31

I am trying to sort the python dictionary based on the values in ascending order. However, if the value is the same then the items should be sorted on the basis of the keys in descending order.

input={-1: 1, 5: 1, -6: 2, 4: 2, 1: 3}
desired_output={5:1, -1:1, 4:2, -6:2, 1:3}

Can anyone suggest an efficient way to do this?

This is the method I have used so far.

dic=dict(sorted(dic.items(),key=lambda x:x[1]))
1 Answers

You can sort by tuple, so just change the key argument to this:

dic=dict(sorted(dic.items(), key=lambda x:(x[1], -x[0])))
Related