Reverse And Invert A Dictionary Mapping In Python

In this post, we will learn about Reverse and inverted dictionary mapping, and to do so we can create a new dictionary in which the keys and values are swapped for the same, we have given an example below.


Reverse And Inverting a Dictionary

Although there are different ways we can reverse the dictionary as key to values and values into keys like using zip and reverse, default dict, and a simple method we have given examples for every method in which we can choose any of the following.

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

# Reverse the original dictionary
reversed_dict = {value: key for key, value in original_dict.items()}

print(reversed_dict)  # Output: {1: 'a', 2: 'b', 3: 'c'}

In this example given we have a dictionary named original dict where the keys are mapped with values and we created another dictionary as reverse dict which is storing the reversed dict means at the place of all the keys we have value and values are replaced by keys.

By Zip And Reverse Method

Let’s have some other ways to perform the same where we used the zip and reversed method and here is an example to show where we can get the task done as per our choice.

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

# Reverse the original dictionary
reversed_dict = dict( zip( original_dict.values(), original_ dict.keys()))

print(reversed_dict)  # Output: {1: 'a', 2: 'b', 3: 'c'}

Here we simply created a zip function for creating a list of values and key tuples which are nothing but driven from the original dictionary. Here we also created another dictionary as a dict to store the updated dictionary.

Using Defaultdict

Here we have given an example where we simply used a default dict to make this reverse

from collections import defaultdict

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

# Reverse the original dictionary
reversed_dict = defaultdict( list)
for key, value in original_dict.items():
    reversed_dict[value].append( key)

print(dict(reversed_dict))  # Output: {1: ['a'], 2: ['b'], 3: ['c']}

Here we used a default dict to create a reversed dict of the dict we created before as original which has a name as original dict.



for learning more about Reverse and inverting a dictionary mapping in Python and to know more visit:  by stack overflow

To learn more about python solutions to different python problems and tutorials for the concepts we need to know to work on python programming along with different ways to solve any generally asked problems: How To Pass-Variables From A Java & Python Client To A Linux/Ubuntu Server Which Is Running C?.

Leave a Comment

%d bloggers like this: