How to reverse order of keys in python dict?

2019-03-12 09:08发布

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?

7条回答
Animai°情兽
2楼-- · 2019-03-12 09:46

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

查看更多
仙女界的扛把子
3楼-- · 2019-03-12 09:48

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'}
查看更多
smile是对你的礼貌
4楼-- · 2019-03-12 09:50

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]
查看更多
来,给爷笑一个
5楼-- · 2019-03-12 09:54

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]

查看更多
Luminary・发光体
6楼-- · 2019-03-12 09:56

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

查看更多
Rolldiameter
7楼-- · 2019-03-12 10:03

Try:

for i in sorted(a.keys(), reverse=True):
    print i
查看更多
登录 后发表回答