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?
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?
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.
Now you can sort the list as normal, e.g.,
a.sort()
and reverse it as well, e.g.,a.reverse()
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:
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:The order keys are iterated in is arbitrary. It was only a coincidence that they were in sorted order.
just try,
INPUT: a = {0:'000000',1:'11111',3:'333333',4:'444444'}
OUTPUT: [4, 3, 1, 0]
Python dict is not ordered in 2.x. But there's an ordered dict implementation in 3.1.
Try: