How to reverse order of keys in python dict?
Asked Answered
B

11

61

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?

Blackcap answered 28/3, 2011 at 6:57 Comment(2)
Dictionaries don't have an order. The keys come out in what appears to be sorted order just by luck (and an implementation nuance that you can't rely on.) There is no inherent order.Shelled
See @rotareti 's answer. Since Python 3.7 dictionary keys have a guaranteed ordering (which is insertion order, not an actual sort). Bye bye unordered dictionary keys.Mneme
C
59

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]
Contumelious answered 28/3, 2011 at 7:1 Comment(1)
You can actually speed the reversed case up a bit by doing sorted(a.keys(), reverse=True) instead of using the reversed() builtin.Spaceman
S
46

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()))
Stebbins answered 26/7, 2019 at 16:21 Comment(3)
Disregarding the extra ) that will cause a SyntaxError, dictviews also only became reversible in Python 3.8, so reversed(my_dict.keys()) will raise a TypeError in Python 3.7.Offhand
@Offhand Thanks for pointing this out! The answer should be fixed now.Stebbins
Small note: In reversed(list(my_dict.keys())), the .keys() can be omitted because the dict iterator returns its keys.Meridithmeriel
N
20

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'}
Noggin answered 28/3, 2011 at 7:0 Comment(1)
Just for future reference, it seems like the dictionaries in Python 3.7+ actually remember the insertion order (source).Lila
V
14

Try:

for i in sorted(a.keys(), reverse=True):
    print i
Velodrome answered 28/3, 2011 at 7:0 Comment(0)
S
6

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

Statolatry answered 28/3, 2011 at 7:3 Comment(1)
+1 for OrderedDict. In fact it is also available in Python 2.7: docs.python.org/library/…Noggin
I
5

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()

Itinerant answered 28/3, 2011 at 7:1 Comment(2)
This will only put the keys in a list. You will loose the values.Noggin
+1 for explaining that all other answers are actually converting to list.Trudytrue
T
2

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 ¢.

Townshend answered 14/12, 2019 at 15:20 Comment(0)
M
2

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])

Mestas answered 29/5, 2020 at 11:12 Comment(0)
O
1

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}
Oysterman answered 3/12, 2020 at 8:27 Comment(0)
M
0
for i in reversed(sorted(a.keys())):
    print i
Moccasin answered 28/3, 2011 at 7:1 Comment(3)
I think this is a "bad" answer because the asker clearly has a misconception about how python dicts function and that misconception should be addressed instead of giving him something that 'looks like' what he wants.Itinerant
You're right, I should have read the question more carefully.Moccasin
Upvote: StackExchange is not a correctional institution. ifLoop shows how to be helpful instead of just correct.Andromache
M
0

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]

Matchless answered 13/9, 2018 at 10:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.