'how to sort a dict by keys and values at the same time? in fact, in my dict, keys are strings and i want to sort alphabetically and values are number

I want to sort the dict below by values firstly from max to min and when two values have the same amount, I want to sort it alphabetically? my problem:

the_dict={ 'Action': 3, 'Romance':2, 'Adventure':1 , 'Comedy': 2 , 'History'=1, 'Horror'=3} 

I have used:

for key, value in sorted(dict.items(), reverse=True, key=lambda x:(x[1], x[0])):
     print(key,':',value)

I have gotten the result below:

'Action': 3
'Horror':3
'Comedy': 2
'Romance':2
'History':1
'Adventure':1

but my idea result is:

'Action': 3
'Horror':3
'Comedy': 2
'Romance':2
'Adventure':1
'History':1

How can I reach my favorite result?



Solution 1:[1]

As your values are int, you can do something like this:

for key, value in sorted(the_dict.items(), key=lambda x: (-x[1], x[0])):
    print(key, ':', value)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1