How to Reverse the Python Dictionary

How to Reverse the Python Dictionary?

In this tutorial, we will learn how to reverse the Python dictionary. Python is a versatile programming language that is valuable for tasks such as scripting, data science, and web development. In Python, a dictionary serves as an unordered collection of data values, functioning like a map. Unlike other data types that can only store a single value as an element, a dictionary retains the key-value pairs. It stores its elements using key-value mapping and employs hashing internally, enabling us to swiftly retrieve a value based on its key.

A reverse Python dictionary is a data structure that allows you to retrieve keys based on their corresponding values. In other words, it provides a way to look up a key by providing its associated value. It is called “reverse” because it reverses the key-value pairs of a regular dictionary.

When working with dictionaries in Python, there may be instances where reversing the order of the dictionaries becomes necessary. This requirement is common in various domains, including web development and everyday programming. Let’s explore potential solutions to this scenario.

RELATED POST: How can I remove a key from a Python Dictionary?

Different Methods to Reverse Python Dictionary

  1. Reverse Python Dictionary by using OrderedDict() and items() Method.
  2. Reverse Python Dictionary by using reversed() and the items() Method.
  3. Reverse Python Dictionary by using a loop and reversed() Method.

1. Reverse Python Dictionary Using OrderedDict() and items() Method

To reverse a Python dictionary using OrderedDict() and the items() method, you can follow these steps:

  • Import the OrderedDict class from the collections module.
  • Create an instance of OrderedDict with the original dictionary’s items in reversed order.
  • Convert the reversed OrderedDict back into a regular dictionary using the dict() function.

Example:

from collections import OrderedDict

original_dict = {'a': 1, 'b': 2, 'c': 3}

reversed_dict = dict(OrderedDict(reversed(list(original_dict.items()))))
print("Original Dictionary :  ",original_dict)
print("Dictionary in Reverse Order :  ",reversed_dict)


Output:

Original Dictionary :   {'a': 1, 'b': 2, 'c': 3}
Dictionary in Reverse Order :   {'c': 3, 'b': 2, 'a': 1}

2. Reverse Python Dictionary Using reversed() and the items() method

To reverse a Python dictionary using reversed() and the items() method, you can follow these steps :

  • Access the key-value pairs of the original dictionary using the items() method. This returns a list of tuples representing the key-value pairs.
  • Apply the reversed() function to the list of tuples obtained in the previous step. This reverses the order of the tuples.
  • Convert the reversed tuples back into a dictionary using the dict() function.

Example :

# Original dictionary
original_dict = {'a': 1, 'b': 2, 'c': 3}
print("Original Dictionary :  ",original_dict)

# Reversing the dictionary using reversed() and items() method
reversed_dict = dict(reversed(list(original_dict.items())))

# Displaying the reversed dictionary
print("Dictionary in Reverse Order :  ",reversed_dict)


Output :

Original Dictionary :   {'a': 1, 'b': 2, 'c': 3}
Dictionary in Reverse Order :   {'c': 3, 'b': 2, 'a': 1}

First, we access the key-value pairs of the original dictionary using the items() method. This method returns a list of tuples, where each tuple represents a key-value pair, such as [(key1, value1), (key2, value2), ...].

Next, we apply the reversed() function to the list of tuples obtained previously. This action effectively reverses the order of the tuples.

Subsequently, the reversed tuples are passed to the dict() function, which creates a new dictionary by utilizing the reversed key-value pairs.

Finally, we print the reversed_dict using the print() function. This displays the reversed dictionary, wherein both the keys and values have been reversed in comparison to the original dictionary.

Check out My Latest post on Developer Helps for some Interesting Insights


3. Reverse Python Dictionary Using a loop and reversed() method

To use a loop and the reversed() method, you can follow these steps:

  • Create an empty dictionary to store the reversed key-value pairs.
  • Iterate over the original dictionary using a for loop.
  • For each key-value pair, add a new entry to the reversed dictionary with the key and value swapped.
  • Return the reversed dictionary

Example:

def reverse_dictionary(original_dict):
    reversed_dict = {}
    for key, value in original_dict.items():
        reversed_dict[value] = key
    return reversed_dict

# Example usage:
original_dict = {'a': 1, 'b': 2, 'c': 3}
print("Original Dictionary :  ",original_dict)

reversed_dict = reverse_dictionary(original_dict)
# Displaying the reversed dictionary
print("Dictionary in Reverse Order :  ",reversed_dict)


Output:

Original Dictionary :   {'a': 1, 'b': 2, 'c': 3}
Dictionary in Reverse Order :   {1: 'a', 2: 'b', 3: 'c'}

In this program, the reverse_dictionary() function takes the original_dict as input. Firstly, it initializes an empty dictionary, reversed_dict, which will store the reversed key-value pairs.

Using a for loop, the function iterates over the original_dict using the items() method. During each iteration, the loop swaps the key and value while creating a new entry in the reversed_dict.

Finally, the function returns the reversed_dict. In the example usage, the original_dict contains keys ‘a’, ‘b’, and ‘c’ with corresponding values 1, 2, and 3. Upon reversing the dictionary, the reversed_dict is displayed, revealing keys 1, 2, and 3, paired with values ‘a’, ‘b’, and ‘c’, respectively.

Discover Our Exciting Courses and Quiz

Enroll now to enhance your skills and knowledge!

Python Online Quiz

Level up your coding skills with our interactive programming quiz!