python - 如果键相等则合并两个字典

标签 python dictionary merge

我有 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/

相关文章:

Python2 json : load using strings instead of unicode

git - 使用 Git 将未 merge 的功能分支 merge 到另一个功能分支

python - 使用 numexpr 优化 numpy 中的数值运算

python - 生成所有可能的交替数字和字母序列

python - 为什么 dict.update(key=value) 不使用 key 引用的字符串?

jquery - 在点击位置移动 map 上的角色

git - 为什么我使用git rebase时,同样的冲突又出现了?

java - 如何在 Eclipse 中合并大型项目?

Python:Xlsxwriter,第一次保存失败后保存文件

python - pandas.interval_range 部分间隔