3

I want to get a list of keys sorted by its values and in case of any ties, sorted alphabetically. I'm able to sort by values. In case of ties, I'm facing issues.

for dictionary:

aDict = {'a':8, 'one' : 1, 'two' : 1, 'three':2, 'c':6,'four':2,'five':1}

I've tried this:

sorted(aDict, key=aDict.get, reverse=True)

which gives me:

['a', 'c', 'three', 'four', 'two', 'five', 'one']

but I want:

['a', 'c', 'four', 'three', 'five', 'one', 'two']

1 Answers1

5

You can use a keyfunction that returns a tuple. The values will be sorted by the second element of the tuple if the first elements are equal.

>>> aDict = {'a':8, 'one' : 1, 'two' : 1, 'three':2, 'c':6,'four':2,'five':1}
>>> sorted(aDict, key=lambda x: (-aDict[x], x))
['a', 'c', 'four', 'three', 'five', 'one', 'two']
timgeb
  • 76,762
  • 20
  • 123
  • 145