1

I am trying to sort a dictionary twice: by descending value, and then the keys alphabetically.

For example,

tally = {"hello": 5, "dog": 12, "cat": 1, "bird": 5, "lion": 5}

I want to output a list, that contains each of these words, sorted by descending value.

output = ["dog", "hello", "bird", "lion", "cat"]

Then within this sorting, subsort them alphabetically As in:

final_result = ["dog", "bird", "hello", "lion", "cat"]

I do not actually need to get the list output, I only need to get final_result. So if there is a way to do that with 1 step, that would be better. So how do I that?

I tried using key = lambda t:t[1] for the initial sorting, but that resulted in a tuple with the keys and values from my dictionary. Now that obviously did not work because I wanted only the words, and also I had no idea how to do the sub sorting in that one.

Thanks in advance for the help.

Ch3steR
  • 20,090
  • 4
  • 28
  • 58
TGamer
  • 529
  • 1
  • 9
  • 26

1 Answers1

4

You can use a custom key to sort according to both conditions. This can be done in a single step by specifying a tuple (-value,key), where by taking the negative sign of the values we get a descending sort:

>>> sorted(tally,key=lambda x: (-tally[x],x))
['dog', 'bird', 'hello', 'lion', 'cat']

The logic (-value,key) is given by @yatu

Ch3steR
  • 20,090
  • 4
  • 28
  • 58
  • Thanks for the 2 of you, not sure why yatu deleted their answer, but anyway I am still confused. This code worked, but i don't know why and how it does so... I am new to Python so I didn't really understand the logic... – TGamer May 05 '20 at 12:49