/  Technology   /  How to reverse order of keys in python dict?

How to reverse order of keys in python dict?

 

Often while working with dictionaries, we might need the reverse order of a dictionary’s keys. We can do this in two ways

  • Using OrderedDict() + reversed() + items()
  • Using reversed() + items()

 

Using OrderedDict() + reversed() + items():

This method is mostly used for older versions of Python as in these, the dictionaries are generally unordered. So we convert them into an ordered one using the OrderedDict().

To learn more about OrderedDict refer this article https://www.i2tutorials.com/are-dictionaries-ordered-in-python/

 

Let us consider a dictionary named x with the following keys and values.

 

Example:

x = {'d':'four', 'e':'five', 'a':'one'}

 

Output:

And now we use the combination of OrderedDict(), reversed() and items() to get the reverse of a dictionary and store it in y as:

 

y = OrderedDict ( reversed (list( x.items ()))

 

Example:

from collections import OrderedDict

x = {'d':'four', 'e':'five', 'a':'one'}
print("The original dictionary : " + str(x))

y = OrderedDict(reversed(list(x.items())))
print("The reversed order dictionary : " + str(y))

 

Output:

Note: The items() function returns all the items of a dictionary. The OrderedDict() function helps in retaining the original order of the dictionary and the reversed() function helps in reversing the elements.

 

As we can see the keys and their respective values’ order has been reversed.

 

Using reversed() + items():

We use this method for the newer versions of Python, in which the original order of the dictionary elements is retained.

We’ll take the same example of dictionary x as above. And use a combination of reversed() and items() functions and store the result in a dictionary y.

 

y = dict ( reversed (list ( x.items() ))) 

 

Example:

x = {'d':'four', 'e':'five', 'a':'one'}
print("The original dictionary : " + str(x))

y = dict(reversed(list(x.items())))
print("The reversed order dictionary : " + str(y))

 

Output:

Leave a comment