How to reverse order of keys in python dict?

This is my code :

a = {0:'000000',1:'11111',3:'333333',4:'444444'}

for i in a:
    print i

it shows:

0
1
3
4

but I want it to show:

4
3
1
0

so, what can I do?


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]

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 reversed() accepts dicts as well, thus you can use:

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

Dictionaries are unordered so you cannot reverse them. The order of the current output is arbitrary.

That said, you can order the keys of course:

for i in sorted(a.keys(), reverse=True):
    print a[i];

but this gives you the reverse order of the sorted keys, not necessarily the reverse order of the keys how they have been added. I.e. it won't give you 1 0 3 if your dictionary was:

a = {3:'3', 0:'0', 1:'1'}

Try:

for i in sorted(a.keys(), reverse=True):
    print i

Python dict is not ordered in 2.x. But there's an ordered dict implementation in 3.1.