我有 2 部词典。
我需要根据键值对将它们合并在一起。如果第一个或第二个字典中的任何键值项不匹配,它们将作为单独的对添加到最终字典中。
最佳答案
可能效率不高但天真的方法可能是遍历每个字典中的项目并添加到新字典中:
Dict1 = {'a': [1, 2, 3], 'b': [5], 'c': [5, 6, 9]}
dict2 = {'a': [4], 'b': [8, 9, 0], 'd': [10, 14, 13]}
# to store final result of dictionary
result = {}
# iterate through each dictionary in list
for dictionary in [Dict1, dict2]:
# iterate through key value of dictionary items
for k,v in dictionary.items():
# if key is already in result dictionary then extend new values
if k in result.keys():
result[k].extend(v)
# else if key is not in dictionary then add key with the first value
else:
result[k] = v
print(result)
结果:
{'d': [10, 14, 13], 'a': [1, 2, 3, 4], 'b': [5, 8, 9, 0], 'c': [5, 6, 9]}
注意 正如@chepner 在下面的评论中指出的那样,上述解决方案更改了 Dict1
因此,使用 deepcopy
可以避免它,而其他is .keys()
在检查字典中是否存在键时不需要:
from copy import deepcopy
Dict1 = {'a': [1, 2, 3], 'b': [5], 'c': [5, 6, 9]}
dict2 = {'a': [4], 'b': [8, 9, 0], 'd': [10, 14, 13]}
# to store final result of dictionary
result = {}
# iterate through each dictionary in list
for dictionary in [deepcopy(Dict1), dict2]:
# iterate through key value of dictionary items
for k,v in dictionary.items():
# if key is already in result dictionary then extend new values
if k in result:
result[k].extend(v)
# else if key is not in dictionary then add key with the first value
else:
result[k] = v
print(result)
关于python - 如果键相等则合并两个字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50380529/