Python|将Python键值合并到列表中
有时,在使用Python时,我们可能会遇到需要从多个字典中获取字典的值以封装到一个字典中的问题。这种类型的问题在我们使用关系数据的领域中很常见,例如在 Web 开发中。让我们讨论一些可以解决这个问题的方法。
方法 #1:使用setdefault()
+ 循环
可以使用嵌套循环并获取字典的每个元素并为新键创建新列表或在出现类似键的情况下附加值来执行此任务。
# Python3 code to demonstrate working of
# Merge Python key values to list
# Using setdefault() + loop
# Initialize list
test_list = [{'gfg' : 2, 'is' : 4, 'best' : 6},
{'it' : 5, 'is' : 7, 'best' : 8},
{'CS' : 10}]
# Printing original list
print("The original list is : " + str(test_list))
# using setdefault() + loop
# Merge Python key values to list
res = {}
for sub in test_list:
for key, val in sub.items():
res.setdefault(key, []).append(val)
# printing result
print("The merged values encapsulated dictionary is : " + str(res))
The original list is : [{‘is’: 4, ‘gfg’: 2, ‘best’: 6}, {‘it’: 5, ‘is’: 7, ‘best’: 8}, {‘CS’: 10}]
The merged values encapsulated dictionary is : {‘is’: [4, 7], ‘it’: [5], ‘gfg’: [2], ‘CS’: [10], ‘best’: [6, 8]}
方法#2:使用列表理解+字典理解
上述组合可用于执行此特定任务。这提供了一种可用于此任务的衬垫。即使它在性能域上可能是有效的。
# Python3 code to demonstrate working of
# Merge Python key values to list
# Using list comprehension + dictionary comprehension
# Initialize list
test_list = [{'gfg' : 2, 'is' : 4, 'best' : 6},
{'it' : 5, 'is' : 7, 'best' : 8},
{'CS' : 10}]
# Printing original list
print("The original list is : " + str(test_list))
# using list comprehension + dictionary comprehension
# Merge Python key values to list
res = {key: list({sub[key] for sub in test_list if key in sub})
for key in {key for sub in test_list for key in sub}}
# printing result
print("The merged values encapsulated dictionary is : " + str(res))
The original list is : [{‘is’: 4, ‘gfg’: 2, ‘best’: 6}, {‘it’: 5, ‘is’: 7, ‘best’: 8}, {‘CS’: 10}]
The merged values encapsulated dictionary is : {‘is’: [4, 7], ‘it’: [5], ‘gfg’: [2], ‘CS’: [10], ‘best’: [6, 8]}