Python|反转字典映射的方法
字典是一个无序、可变和索引的集合。在Python中,字典是用大括号编写的,它们有键和值。它广泛用于日常编程、Web 开发和机器学习。
让我们讨论几种反转字典映射的方法。
方法#1:使用字典理解。
# Python code to demonstrate
# how to invert mapping
# using dict comprehension
# initialising dictionary
ini_dict = {101: "akshat", 201 : "ball"}
# print initial dictionary
print("initial dictionary : ", str(ini_dict))
# inverse mapping using dict comprehension
inv_dict = {v: k for k, v in ini_dict.items()}
# print final dictionary
print("inverse mapped dictionary : ", str(inv_dict))
输出:
initial dictionary : {201: 'ball', 101: 'akshat'}
inverse mapped dictionary : {'ball': 201, 'akshat': 101}
方法 #2:使用dict.keys()
和dict.values()
# Python code to demonstrate
# how to invert mapping
# using zip and dict functions
# initialising dictionary
ini_dict = {101: "akshat", 201 : "ball"}
# print initial dictionary
print("initial dictionary : ", str(ini_dict))
# inverse mapping using zip and dict functions
inv_dict = dict(zip(ini_dict.values(), ini_dict.keys()))
# print final dictionary
print("inverse mapped dictionary : ", str(inv_dict))
输出:
initial dictionary : {201: 'ball', 101: 'akshat'}
inverse mapped dictionary : {'ball': 201, 'akshat': 101}
方法 #3:使用map()
和反转
# Python code to demonstrate
# how to invert mapping
# using map and reversed
# initialising dictionary
ini_dict = {101: "akshat", 201 : "ball"}
# print initial dictionary
print("initial dictionary : ", str(ini_dict))
# inverse mapping using map and reversed
inv_dict = dict(map(reversed, ini_dict.items()))
# print final dictionary
print("inverse mapped dictionary : ", str(inv_dict))
输出:
initial dictionary : {201: 'ball', 101: 'akshat'}
inverse mapped dictionary : {'akshat': 101, 'ball': 201}
方法 #4:使用 lambda
# Python code to demonstrate
# how to invert mapping
# using lambda
# initialising dictionary
ini_dict = {101 : "akshat", 201 : "ball"}
# print initial dictionary
print("initial dictionary : ", str(ini_dict))
# inverse mapping using lambda
lambda ini_dict: {v:k for k, v in ini_dict.items()}
# print final dictionary
print("inverse mapped dictionary : ", str(ini_dict))
输出:
initial dictionary : {201: 'ball', 101: 'akshat'}
inverse mapped dictionary : {201: 'ball', 101: 'akshat'}