Sorting a dictionary by its value, and then its key if values are equal then outputting a list

python, sorting

Solution

Sorting is guaranteed to be stable in Python, so all you have to do is sort twice: first on the key, then on the value.

sorted_pairs = sorted(sorted(map.iteritems()), key=operator.itemgetter(1), reverse=True)

To get just the keys from this output you can use a list comprehension:

[k for k,v in sorted_pairs]

P.S. don't name your variables the same as Python types or you're going to be very surprised some day.

Problem

``` map={"a":5, "b":2, "c":7, "d":5, "e":5} ``` output should be: ``` ['c', 'a', 'd', 'e', 'b'] ``` So, the code should first assort the dictionary in descending order by its value, and then if its value is the same it should sort by the key in ascending order. So far I have... ``` newmap=map newmap=sorted(newmap.iteritems(), key=operator.itemgetter(1,0),reverse=True) print newmap ``` This gives me the output `[('c', 7), ('e', 5), ('d', 5), ('a', 5), ('b', 2)]`. So, I need to get the e, d, a in ascending order... without messing up the sorts of the numbers. How do I do this?

Original source