How to reverse order of keys in python dict?

Since Python 3.7, dicts preserve order, which means you can do this now:

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

for k in reversed(list(my_dict.keys())):
    print(k)

Output:

b
c
a

Since Python 3.8, the built-in function reversed() accepts dicts as well.

Here's an example of how you can use it to iterate:

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

for k in reversed(my_dict):
    print(k)

Here's an example of how you can replace your dict with a reversed dict:

my_dict = dict(reversed(my_dict.items()))

Note: this answer is only true for Python < 3.7. Dicts are insertion ordered starting in 3.7 (and CPython 3.6 as an implementation detail).


The order keys are iterated in is arbitrary. It was only a coincidence that they were in sorted order.

>>> a = {0:'000000',1:'11111',3:'333333',4:'444444'}
>>> a.keys()
[0, 1, 3, 4]
>>> sorted(a.keys())
[0, 1, 3, 4]
>>> reversed(sorted(a.keys()))
<listreverseiterator object at 0x02B0DB70>
>>> list(reversed(sorted(a.keys())))
[4, 3, 1, 0]