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?