在Python中的字典列表中组合键
有时,在使用Python字典时,我们可能会遇到一个问题,即我们需要将具有相似键的列表中的字典合并。这类问题可能出现在数据优化领域。让我们讨论一种可以执行此任务的方式。
Input : test_list = [{‘a’: 6}, {‘b’: 2}, {‘a’: 9}, {‘b’: 7}]
Output : [{‘b’: 2, ‘a’: 6}, {‘b’: 7, ‘a’: 9}]
Input : test_list = [{‘a’: 8}, {‘a’: 2}, {‘a’: 3}]
Output : [{‘a’: 8}, {‘a’: 2}, {‘a’: 3}]
方法:循环+ **
运算符
上述功能的组合可以用来解决这个问题。在此,我们使用蛮力构造一个新字典并仅在当前未添加的情况下添加键。合并字典的任务是通过使用“**”运算符解包初始字典,然后使用通常的字典初始化构造 {} 再次使用没有重复键和新键的字典进行打包。
# Python3 code to demonstrate working of
# Merge Similar Dictionaries in List
# Using loop + "**" operator
# initializing list
test_list = [{'gfg' : 1}, {'is' : 2}, {'best' : 3},
{'gfg' : 5}, {'is' : 17}, {'best' : 14},
{'gfg' : 7}, {'is' : 8}, {'best' : 10},]
# printing original list
print("The original list is : " + str(test_list))
# Merge Similar Dictionaries in List
# Using loop + "**" operator
res = [{}]
for sub in test_list:
if list(sub)[0] not in res[-1]:
res[-1] = {**res[-1], **sub}
else:
res.append(sub)
# printing result
print("The merged dictionaries : " + str(res))
The original list is : [{‘gfg’: 1}, {‘is’: 2}, {‘best’: 3}, {‘gfg’: 5}, {‘is’: 17}, {‘best’: 14}, {‘gfg’: 7}, {‘is’: 8}, {‘best’: 10}]
The merged dictionaries : [{‘best’: 3, ‘is’: 2, ‘gfg’: 1}, {‘best’: 14, ‘is’: 17, ‘gfg’: 5}, {‘best’: 10, ‘is’: 8, ‘gfg’: 7}]