Home > Enterprise >  How to sort the values of a dictionary in descending order and the keys alphabetically
How to sort the values of a dictionary in descending order and the keys alphabetically

Time:11-06

How do we sort values in a dictionary in descending order, and if there are two similar values, sort the key of those values alphabetically?

Like the following example :

Input = {'robert':13, 'walter':17, 'andrew':16, 'adrian':16, 'simon':15, 'santiago':15} 
Output = {'walter':17, 'adrian':16, 'andrew':16, 'santiago':15, 'simon':15}

CodePudding user response:

You can use sorted and set key what you want like below:

(here first you want to sort descending on value then sort ascending on key if values are equal):

>>> dct = {'robert':13, 'walter':17, 'andrew':16, 'adrian':16, 'simon':15, 'santiago':15}

>>> dict(sorted(dct.items(), key=lambda x: (-x[1],x[0])))
{'walter': 17,
 'adrian': 16,
 'andrew': 16,
 'santiago': 15,
 'simon': 15,
 'robert': 13}

CodePudding user response:

you can sort values of dictionary in this way:

output = dict(sorted(inp.items(), key=lambda item: item[1], reverse=True))

output:

{'walter': 17, 'andrew': 16, 'adrian': 16, 'simon': 15, 'santiago': 15, 'robert': 13}

  • Related