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.
# Python code to demonstrate# how to invert mapping # using dict comprehension # initialising dictionaryini_dict = {101: "akshat", 201 : "ball"} # print initial dictionaryprint("initial dictionary : ", str(ini_dict)) # inverse mapping using dict comprehensioninv_dict = {v: k for k, v in ini_dict.items()} # print final dictionaryprint("inverse mapped dictionary : ", str(inv_dict)) |
initial dictionary : {201: 'ball', 101: 'akshat'}
inverse mapped dictionary : {'ball': 201, 'akshat': 101}
Method #2: Using dict.keys() and dict.values()
# Python code to demonstrate# how to invert mapping # using zip and dict functions # initialising dictionaryini_dict = {101: "akshat", 201 : "ball"} # print initial dictionaryprint("initial dictionary : ", str(ini_dict)) # inverse mapping using zip and dict functionsinv_dict = dict(zip(ini_dict.values(), ini_dict.keys())) # print final dictionaryprint("inverse mapped dictionary : ", str(inv_dict)) |
initial dictionary : {201: 'ball', 101: 'akshat'}
inverse mapped dictionary : {'ball': 201, 'akshat': 101}
Method #3: Using map() and reversed
# Python code to demonstrate# how to invert mapping # using map and reversed # initialising dictionaryini_dict = {101: "akshat", 201 : "ball"} # print initial dictionaryprint("initial dictionary : ", str(ini_dict)) # inverse mapping using map and reversedinv_dict = dict(map(reversed, ini_dict.items())) # print final dictionaryprint("inverse mapped dictionary : ", str(inv_dict)) |
initial dictionary : {201: 'ball', 101: 'akshat'}
inverse mapped dictionary : {'akshat': 101, 'ball': 201}
Method #4: Using lambda
# Python code to demonstrate# how to invert mapping # using lambda # initialising dictionaryini_dict = {101 : "akshat", 201 : "ball"} # print initial dictionaryprint("initial dictionary : ", str(ini_dict)) # inverse mapping using lambdalambda ini_dict: {v:k for k, v in ini_dict.items()} # print final dictionaryprint("inverse mapped dictionary : ", str(ini_dict)) |
initial dictionary : {201: 'ball', 101: 'akshat'}
inverse mapped dictionary : {201: 'ball', 101: 'akshat'}
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course


