简体   繁体   中英

How to reverse order of keys in python dict?

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?

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]

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 reversed() accepts dicts as well, thus you can use:

for k in reversed(my_dict):
    print(k)

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. Ie it won't give you 1 0 3 if your dictionary was:

a = {3:'3', 0:'0', 1:'1'}

Try:

for i in sorted(a.keys(), reverse=True):
    print i

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, eg, a.sort() and reverse it as well, eg, a.reverse()

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

for i in reversed(sorted(a.keys())):
    print i

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

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

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}

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM