如果键相等,则合并两个词典

时间:2018-05-16 22:01:29

标签: python dictionary merge

我有2本词典。

我需要根据键:值对将它们合并在一起。如果第一个或第二个字典中的任何键:值项不匹配,则将它们作为单独的对添加到最终字典中。

4 个答案:

答案 0 :(得分:1)

当项目不在您的列表中时,您可以使用dict.get返回空列表。这允许通过循环现有键来获得具有单个字典理解的所需输出。

d1 = {'a': [1, 2, 3], 'b': [5], 'c': [5, 6, 9]}
d2 = {'a': [4], 'b': [8, 9, 0], 'd': [10, 14, 13]}

output = {k: d1.get(k, []) + d2.get(k, []) for k in {*d1, *d2}}
# output: {'a': [1, 2, 3, 4], 'b': [5, 8, 9, 0], 'c': [5, 6, 9], 'd': [10, 14, 13]}

答案 1 :(得分:1)

可能效率不高但天真的方式可能是迭代每个字典中的项目并添加新词典:

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会避免它,而其他的是.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)

答案 2 :(得分:0)

您可以使用defaultdict

final_dict = defaultdict(list)

for d in [Dict1, dict2]:
    for k, v in d.items():
        final_dict[k].extend(v)

结果是:

defaultdict(<type 'list'>, {'a': [1, 2, 3, 4], 'c': [5, 6, 9], 'b': [5, 8, 9, 0], 'd': [10, 14, 13]})

答案 3 :(得分:-1)

您可以使用<Back

itertools.groupby

输出:

import itertools
dict1 = {'a': [1, 2, 3], 'b': [5], 'c': [5, 6, 9]}
dict2 = {'a': [4], 'b': [8, 9, 0], 'd': [10, 14, 13]}
new_l = [[a, list(b)] for a, b in itertools.groupby(sorted(list(dict1.items())+list(dict2.items()), key=lambda x:x[0]), key=lambda x:x[0])]
final_result = {a:list(itertools.chain.from_iterable([c for _, c in b])) for a, b in new_l}
相关问题