以下是一个按字典中键的值合并两个字典列表的示例代码:
def merge_dicts(dicts1, dicts2):
merged = {}
for d in dicts1 + dicts2:
for key, value in d.items():
if key not in merged:
merged[key] = value
else:
merged[key] += value
return merged
dicts1 = [{'a': 1, 'b': 2}, {'c': 3}]
dicts2 = [{'a': 4}, {'b': 5, 'd': 6}]
merged_dicts = merge_dicts(dicts1, dicts2)
print(merged_dicts)
输出结果为:
{'a': 5, 'b': 7, 'c': 3, 'd': 6}
在上述示例中,我们定义了一个名为merge_dicts
的函数,该函数接受两个字典列表作为参数,并返回合并后的字典。我们通过迭代两个字典列表中的字典,并使用items()
方法遍历每个字典中的键值对。如果键不存在于合并的字典merged
中,我们将该键值对添加到merged
中;否则,我们将新值与旧值相加。最后,我们输出合并后的字典。
上一篇:按字典值对字典进行排序
下一篇:按字典中字典的排序