What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

How to Reverse a Dictionary in Python?

  • Dec 17, 2021
  • 5 Minutes Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Adrita Das
How to Reverse a Dictionary in Python?

 

Python is a useful programming language for scripting, data science, and web development. In Python, a dictionary is an unordered collection of data values, similar to a map, that retains the key: value pair, unlike other data types that only hold a single value as an element. A dictionary stores its elements in key-value mapping style and uses hashing internally; as a result, we can rapidly retrieve a value from the dictionary by its key.

When working with dictionaries in python, we may encounter situations where we need to reverse the order of the dictionaries. It is common with applications in a number of domains, including web development and day-to-day programming. Let's look at some possible solutions to this situation and learn how python reverse dictionary.

Methods to Reverse Dictionary in Python

Reversing a dictionary is not the same as reversing a list; it entails inverting or switching the dictionary's key and value parts, basically swapping them for whatever purpose the developer has in mind. Below are 3 methods by which you can reverse a dictionary in python:

1) Using OrderedDict() and items() method

This method is for Python versions prior to 2.7. Because older versions don't retain the ordered nature of dictionaries and so, you'll need to convert to OrderedDict to complete this work. Later you make use of a reversed() function which is an in-built python method that takes an argument as the sequence data types like tuple, lists, dictionaries, etc and returns the reverse of it. Remember that reversed() method does not modify the original iterator.

Note that before beginning to reverse the dictionary using this method, you have to import the OrderedDict library from the collections module of python using the "from..import" keyword as shown in the below example.

For example:

from collections import OrderedDict

# initializing dictionary
test_dict = {'silver' : 4, 'gold' : 2, 'diamond' : 5} 
print("The original dictionary : " + str(test_dict)) 
res = OrderedDict(reversed(list(test_dict.items())))

# printing dictionary in reversed order
print("The dictionary in reversed order : " + str(res)) 

 

Ouput:

The original dictionary : {'silver': 4, 'gold': 2, 'diamond': 5}
The dictionary in reversed order : OrderedDict([('diamond', 5), ('gold', 2), ('silver', 4)])

 

2) Using reversed() and items() method

This problem can be solved using a mixture of the preceding functions. This is for newer python versions 3.6+ that have a dictionary in the incoming element order. Therefore, we do not have to make use of the OrderedDict() method for preserving the order of the dictionary.

For example:

# initializing dictionary
test_dict = {'silver' : 4, 'gold' : 2, 'diamond' : 5}
  
# printing original dictionary
print("The original dictionary : " + str(test_dict))
res =dict(reversed(list(test_dict.items())))
  
# printing reversed order dictionary
print("The reversed order dictionary : " + str(res)) 

 

Output:

The original dictionary : {'silver': 4, 'gold': 2, 'diamond': 5}
The reversed order dictionary : {'diamond': 5, 'gold': 2, 'silver': 4}

 

3) Using loop and reversed() method

In this method, you initialize a new empty dictionary for storing the reversed items of the original dictionary. Later, using the for loop you traverse through the original list and store every key-value pair in the new empty dictionary after reversing it using reversed() method. Check out the example below for a better understanding.

For example:

test_dict1 = {'silver': 4, 'gold': 2, 'diamond': 5}
print("The original dictionary ", test_dict1)
test_dict2 = {}
for key in reversed(test_dict1):
    test_dict2[key] = test_dict1[key]
print("The reversed order dictionary ", test_dict2)

 

Output:

The original dictionary  {'silver': 4, 'gold': 2, 'diamond': 5}
The reversed order dictionary  {'diamond': 5, 'gold': 2, 'silver': 4}

 

Summary

In summary, dictionaries are python's version of an associative array and widely used data structure in the technical domain. As dictionaries are mainly used during python programming, there are times when you wish to reverse it externally. Here we have presented various methods by which you can reverse the dictionaries in python effortlessly and make your programming efficient.

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Adrita Das
I am Adrita Das, a Biomedical Engineering student and technical content writer with a background in Computer Science. I am pursuing this goal through a career in life science research, augmented with computational techniques. I am passionate about technology and it gives immense happiness to share my knowledge through the content I make.