59

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?

jchanger
  • 739
  • 10
  • 29
zjm1126
  • 34,604
  • 53
  • 121
  • 166
  • 8
    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. – S.Lott Mar 28 '11 at 10:01
  • 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. – NeilG Mar 21 '23 at 08:14

11 Answers11

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]
SingleNegationElimination
  • 151,563
  • 33
  • 264
  • 304
  • 33
    You can actually speed the reversed case up a bit by doing `sorted(a.keys(), reverse=True)` instead of using the `reversed()` builtin. – ncoghlan Mar 28 '11 at 10:54
44

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()))
Pikamander2
  • 7,332
  • 3
  • 48
  • 69
Rotareti
  • 49,483
  • 23
  • 112
  • 108
  • 2
    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. – Harmon758 Oct 19 '19 at 15:24
  • @Harmon758 Thanks for pointing this out! The answer should be fixed now. – Rotareti Oct 21 '19 at 11:56
  • Small note: In `reversed(list(my_dict.keys()))`, the `.keys()` can be omitted because the dict iterator returns its keys. – Hugues Dec 06 '21 at 02:42
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'}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 6
    Just for future reference, it seems like the dictionaries in Python 3.7+ actually remember the insertion order [(source)](https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6). – Farzad Abdolhosseini Dec 04 '18 at 23:54
13

Try:

for i in sorted(a.keys(), reverse=True):
    print i
Neil G
  • 32,138
  • 39
  • 156
  • 257
6

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

Rumple Stiltskin
  • 9,597
  • 1
  • 20
  • 25
  • 1
    +1 for OrderedDict. In fact it is also available in Python 2.7: http://docs.python.org/library/collections.html#collections.OrderedDict – Felix Kling Mar 28 '11 at 08:14
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()

Chris W.
  • 37,583
  • 36
  • 99
  • 136
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 ¢.

Fabio Mendes Soares
  • 1,357
  • 5
  • 20
  • 30
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])

A H
  • 2,164
  • 1
  • 21
  • 36
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}
SYED FAISAL
  • 495
  • 5
  • 8
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]

Jai K
  • 375
  • 1
  • 4
  • 12
0
for i in reversed(sorted(a.keys())):
    print i
Simon
  • 12,018
  • 4
  • 34
  • 39
  • 1
    I think this is a "bad" answer because the asker clearly has a misconception about how python `dict`s function and that misconception should be addressed instead of giving him something that 'looks like' what he wants. – Chris W. Mar 28 '11 at 07:04
  • You're right, I should have read the question more carefully. – Simon Mar 28 '11 at 07:36
  • Upvote: StackExchange is not a correctional institution. ifLoop shows how to be helpful instead of just correct. – Florian Heigl Dec 12 '14 at 19:25