How do you sort a dictionary by key from highest to lowest

Question:

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?

Asked By: Robert Selangor

||

Answers:

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?

Answered By: Chris
dict(sorted(dictionary.items(), reverse=True))

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

Answered By: soumya-kole
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.