VOOZH about

URL: https://www.geeksforgeeks.org/python/python-ways-to-invert-mapping-of-dictionary/

⇱ Python | Ways to invert mapping of dictionary - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python | Ways to invert mapping of dictionary

Last Updated : 11 Jul, 2025

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. 

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() 

Output:
initial dictionary : {201: 'ball', 101: 'akshat'}
inverse mapped dictionary : {'ball': 201, 'akshat': 101}

Method #3: Using map() and reversed 

Output:
initial dictionary : {201: 'ball', 101: 'akshat'}
inverse mapped dictionary : {'akshat': 101, 'ball': 201}

Method #4: Using lambda 

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

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

Comment