Python - 词典中反向映射的方法


无序、可变、索引的集合是词典。在 Python 中,词典由花括号标识,且具有键和值。它广泛应用于日常编程、web 开发和机器学习。

示例

 实操演示

# using dict comprehension
# initialising dictionary
ini_dict = {101: "vishesh", 201 : "laptop"}
# 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))
# using zip and dict functions
# initialising dictionary
ini_dict = {101: "vishesh", 201 : "laptop"}
# 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))
# 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))
# 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: 'laptop', 101: 'vishesh'}")
('inverse mapped dictionary : ', "{'laptop': 201, 'vishesh': 101}")
('initial dictionary : ', "{201: 'laptop', 101: 'vishesh'}")
('inverse mapped dictionary : ', "{'laptop': 201, 'vishesh': 101}")
('initial dictionary : ', "{201: 'ball', 101: 'akshat'}")
('inverse mapped dictionary : ', "{'ball': 201, 'akshat': 101}")
('initial dictionary : ', "{201: 'ball', 101: 'akshat'}")
('inverse mapped dictionary : ', "{201: 'ball', 101: 'akshat'}")

更新时间: 2020 年 8 月 6 日

259 次浏览

开启您的职业之路

完成课程,获取认证

开始
广告
© . All rights reserved.