Python | Ways to invert mapping of dictionary
Dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. It is widely used in day to day programming, web development, and machine learning. Let’s discuss a few ways to invert mapping of a dictionary.
Method #1: Using Dictionary Comprehension.
Python3
ini_dict = { 101 : "akshat", 201 : "ball"}
print ("initial dictionary : ", str (ini_dict))
inv_dict = {v: k for k, v in ini_dict.items()}
print ("inverse mapped dictionary : ", str (inv_dict))
|
Output:
initial dictionary : {201: 'ball', 101: 'akshat'}
inverse mapped dictionary : {'ball': 201, 'akshat': 101}
Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(n), to store the keys and values in dictionary.
Method #2: Using dict.keys() and dict.values()
Python3
ini_dict = { 101 : "akshat", 201 : "ball"}
print ("initial dictionary : ", str (ini_dict))
inv_dict = dict ( zip (ini_dict.values(), ini_dict.keys()))
print ("inverse mapped dictionary : ", str (inv_dict))
|
Output:
initial dictionary : {201: 'ball', 101: 'akshat'}
inverse mapped dictionary : {'ball': 201, 'akshat': 101}
Method #3: Using map() and reversed
Python3
ini_dict = { 101 : "akshat", 201 : "ball"}
print ("initial dictionary : ", str (ini_dict))
inv_dict = dict ( map ( reversed , ini_dict.items()))
print ("inverse mapped dictionary : ", str (inv_dict))
|
Output:
initial dictionary : {201: 'ball', 101: 'akshat'}
inverse mapped dictionary : {'akshat': 101, 'ball': 201}
Method #4: Using lambda
Python3
ini_dict = { 101 : "akshat", 201 : "ball"}
print ("initial dictionary : ", str (ini_dict))
lambda ini_dict: {v:k for k, v in ini_dict.items()}
print ("inverse mapped dictionary : ", str (ini_dict))
|
Output:
initial dictionary : {201: 'ball', 101: 'akshat'}
inverse mapped dictionary : {201: 'ball', 101: 'akshat'}
The time complexity of this code is O(n), where n is the number of key-value pairs in the dictionary ini_dict. dictionary.
The auxiliary space complexity of this code is O(n), where n is the number of key-value pairs in the dictionary ini_dict.
Method #5: Using the zip function and dictionary constructor:
Approach:
- Use the zip function to create a list of tuples with the original dictionary’s values and keys
- Pass the list of tuples to the dictionary constructor to create the inverted dictionary
- Return the inverted dictionary
Python3
original_dict = { "a" : 1 , "b" : 2 , "c" : 3 }
inverted_dict = dict ( zip (original_dict.values(), original_dict.keys()))
print (inverted_dict)
|
Output
{1: 'a', 2: 'b', 3: 'c'}
Time complexity: O(n), where n is the number of key-value pairs in the dictionary
Space complexity: O(n), where n is the number of key-value pairs in the dictionary
Last Updated :
27 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...