Python – 将键值映射到字典
有时,在处理Python记录时,我们可能会遇到需要提取键值作为所需的字典值的问题。这可以应用于我们需要减少数据存储的领域和 Web 开发领域。让我们讨论可以执行此任务的某些方式。
方法#1:使用字典理解
这是我们可以解决这个问题的方法之一。在此,我们迭代列表键并使用字典理解构造所需键值对的字典。
# Python3 code to demonstrate working of
# Mapping key values to Dictionary
# Using dictionary comprehension
# initializing list
test_list = [{'name' : 'Manjeet', 'age' : 23},
{'name' : 'Akshat', 'age' : 22},
{'name' : 'Nikhil', 'age' : 21}]
# printing original list
print("The original list is : " + str(test_list))
# Mapping key values to Dictionary
# Using dictionary comprehension
res = {sub['name'] : sub['age'] for sub in test_list}
# printing result
print("The flattened dictionary is : " + str(dict(res)))
输出 :
The original list is : [{‘age’: 23, ‘name’: ‘Manjeet’}, {‘age’: 22, ‘name’: ‘Akshat’}, {‘age’: 21, ‘name’: ‘Nikhil’}]
The flattened dictionary is : {‘Manjeet’: 23, ‘Akshat’: 22, ‘Nikhil’: 21}
方法 #2:使用dict() + values()
上述功能的组合也可以用来解决这个问题。在此,我们使用 dict() 执行到字典的转换,并使用 values() 提取字典值。
# Python3 code to demonstrate working of
# Mapping key values to Dictionary
# Using dict() + values()
# initializing list
test_list = [{'name' : 'Manjeet', 'age' : 23},
{'name' : 'Akshat', 'age' : 22},
{'name' : 'Nikhil', 'age' : 21}]
# printing original list
print("The original list is : " + str(test_list))
# Mapping key values to Dictionary
# Using dict() + values()
res = dict(sub.values() for sub in test_list)
# printing result
print("The flattened dictionary is : " + str(dict(res)))
输出 :
The original list is : [{‘age’: 23, ‘name’: ‘Manjeet’}, {‘age’: 22, ‘name’: ‘Akshat’}, {‘age’: 21, ‘name’: ‘Nikhil’}]
The flattened dictionary is : {‘Manjeet’: 23, ‘Akshat’: 22, ‘Nikhil’: 21}