Reversing the order of key-value pairs in a dictionary (Python)

How do I reorder dictionary key-value pairs in Python? For example, I have this dictionary:

{"a":1, "b":2, "c":3} 

I want to change it so that it returns:

 {"c":3, "b":2, "a":1} 

Is there a function that I have not heard about this that can do this? Some lines of code are also good.

+5
source share
4 answers

The dictionary makes no sense in ordering, so your key / value pairs are not ordered in any format.

If you want to preserve the order of the keys, you should use collections.OrderedDict from the beginning, instead of the usual dictionary, Example -

 >>> from collections import OrderedDict >>> d = OrderedDict([('a',1),('b',2),('c',3)]) >>> d OrderedDict([('a', 1), ('b', 2), ('c', 3)]) 

OrderedDict will keep the order in which keys were entered into the dictionary. In the above case, this would be the order in which the keys existed in the list - [('a',1),('b',2),('c',3)] - 'a' -> 'b' -> 'c'

Then you can get the reverse order of the keys with reversed(d) , Example -

 >>> dreversed = OrderedDict() >>> for k in reversed(d): ... dreversed[k] = d[k] ... >>> dreversed OrderedDict([('c', 3), ('b', 2), ('a', 1)]) 
+7
source

The dictionary uses a Hashmap to store keys and corresponding values.

Take a look: Is the Python dictionary an example of a hash table?

Everything related to the hash has no order.

You can do this with this:

 d = {} d['a']=1 d['b']=2 d['c']=3 d['d']=4 print d for k,v in sorted(d.items(),reverse = True): print k,v 

d.items() returns a list of tuples: [('a', 1), ('c', 3), ('b', 2), ('d', 4)] and k,v gets the values ​​in tuples to repeat the cycle. sorted() returns a sorted list, while you cannot use d.items().sort() , which does not return, but instead tries to overwrite d.items() .

0
source

This will work Based on Venkateshwara, which did not work for me "as is".

 def reverse(self): a = self.yourdict.items() b = list(a) # cast to list from dict_view b.reverse() # actual reverse self.yourdict = dict(b) # push back reversed values 
0
source
 d={"a":1, "b":2, "c":3} x={} for i in sorted(d.keys(),reverse=True): x[i]=d[i] print(x) 
0
source

All Articles