Home > Back-end >  How do you sort a dictionary by key from highest to lowest
How do you sort a dictionary by key from highest to lowest

Time:10-24

Hi I have a dictionary that is currently the one below:

dictionary={1:'a',2:'b',3:'c'}

my desired output is to have a dictionary with the highest keys to the left and the lowest keys to the right like below:

dictionary={3:'c',2:'b',1:'a'}

how do you do that in python 3.7?

CodePudding user response:

dict(sorted(dictionary.items(), reverse=True))

This is duplicate of How do I sort a dictionary by key?

CodePudding user response:

You want to get the keys from the dictionary with dictionary.keys(), then sort it in reverse with sorted(dictionary.keys(), reverse=True), and then you can use that in a dictionary comprehension:

{k: dictionary[k] for k in sorted(dictionary.keys(), reverse=True)}
# {3: 'c', 2: 'b', 1: 'a'}

Of course, if we use sorted on a dict it will return the sorted keys anyway, so we can simplify this slightly to:

{k: dictionary[k] for k in sorted(dictionary, reverse=True)}
# {3: 'c', 2: 'b', 1: 'a'}

This does seems like an XY problem, though. You may want to consider why it matters what order the keys are in? How does that affect your program?

  • Related