Reputation: 637
I want to get a sorted list of keys from a dictionary in python (My dictionary is of int to int mapping). I want the values to be sorted in ascending. But in case of collision (same value), I want the keys to be sorted by the numeric value of the key. The following piece of code does that
key=lambda x: (dict[x],x)
However, I want the ordering of the values in descending and ordering of the keys (only in case of collision) to be descending. I can apply the reverse parameter, but that will work on both key and its value in the same way.
Is there any way to do it separately?
Example
>>> my_dict = {1:5, 2:4, 3:5, 26:3, 5:2, 6:4, 8:3}
>>> my_dict
{1: 5, 2: 4, 3: 5, 5: 2, 6: 4, 8: 3, 26: 3}
>>> sorted_list = sorted(my_dict, key=my_dict.get)
>>> print sorted_list
[5, 8, 26, 2, 6, 1, 3]
I want the output to be [5, 26, 8, 6, 2, 3, 1]
Upvotes: 1
Views: 3341
Reputation: 353059
You have a few options:
>>> my_dict = {1:5, 2:4, 3:5, 26:3, 5:2, 6:4, 8:3}
>>> sorted(my_dict, key=lambda x: (my_dict[x], -x))
[5, 26, 8, 6, 2, 3, 1]
>>> sorted(sorted(my_dict)[::-1], key=my_dict.get)
[5, 26, 8, 6, 2, 3, 1]
>>> sorted(sorted(my_dict, reverse=True), key=my_dict.get)
[5, 26, 8, 6, 2, 3, 1]
The first depends upon the keys being numerical (or at least something which you can negate like this), which is less general than the last two, which use only the fact that the sort is stable.
Upvotes: 5