How to reverse order of keys in python dict?

Question:

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?

Asked By: zjm1126

||

Answers:

Try:

for i in sorted(a.keys(), reverse=True):
    print i
Answered By: Neil G

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'}
Answered By: Felix Kling
for i in reversed(sorted(a.keys())):
    print i
Answered By: Simon

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]

Python dictionaries don’t have any ‘order’ associated with them. It’s merely a ‘coincidence’ that the dict is printing the same order. There are no guarantees that items in a dictionary with come out in any order.

If you want to deal with ordering you’ll need to convert the dictionary to a list.

a = list(a) # keys in list
a = a.keys() # keys in list
a = a.values() # values in list
a = a.items() # tuples of (key,value) in list

Now you can sort the list as normal, e.g., a.sort() and reverse it as well, e.g., a.reverse()

Answered By: Chris W.

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

Answered By: Rumple Stiltskin

just try,

INPUT: a = {0:’000000′,1:’11111′,3:’333333′,4:’444444′}

[x for x in sorted(a.keys(), reverse=True)]

OUTPUT: [4, 3, 1, 0]

Answered By: Jai K

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()))
Answered By: Rotareti

In Python 3.6, which I am using, I reversed the order of keys with their respective values with the help of function update.

original_dict={'A':0,'C':2,'B':1}
new_dict={}
for k,v in original_dict.items():
    dict_element={k:v}
    dict_element.update(new_dict)
    new_dict=dict_element

print(new_dict)

It should print out:

{'B':1,'C':2,'A':0}

My 2 ยข.

Answered By: Fabio Mendes Soares

If you want to preserve the insertion order and not the alphabetical ordering, then you can use:

dict(list(your_dict.keys())[::-1])

Or for the whole dictionary:

dict(list(your_dict.items())[::-1])

Answered By: A H

If you have a dictionary like this

{'faisal2': 2, 'umair': 2, 'fais': 1, 'umair2': 1, 'trending': 2, 'apple': 2, 'orange': 2}

and you want to reverse sort dictionary you can use:

dict(sorted(counts.items(), key=lambda item: item[1],reverse=True))

output will be:

{'faisal2': 2, 'umair': 2, 'trending': 2, 'apple': 2, 'orange': 2, 'fais': 1, 'umair2': 1}
Answered By: SYED FAISAL
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.