如何合并具有相同键名的两个词典

时间:2013-11-08 15:02:27

标签: python dictionary

我是Python的新手,我正在尝试编写一个将在python中合并两个字典对象的函数。 例如

dict1 = {'a':[1], 'b':[2]}
dict2 = {'b':[3], 'c':[4]}

我需要制作一个新的合并字典

dict3 = {'a':[1], 'b':[2,3], 'c':[4]}

函数还应该使用参数“conflict”(设置为True或False)。当冲突设置为False时,上面就可以了。当conflict设置为True时,代码将合并这样的字典:

dict3 = {'a':[1], 'b_1':[2], 'b_2':[3], 'c':[4]}

我试图附加2个词典,但不确定如何以正确的方式进行。

for key in dict1.keys():
    if dict2.has_key(key):
        dict2[key].append(dict1[key])

2 个答案:

答案 0 :(得分:9)

如果您想要一个不会改变原始dicts并监视名称冲突的合并副本,您可能想尝试这个解决方案:

#! /usr/bin/env python3
import copy
import itertools


def main():
    dict_a = dict(a=[1], b=[2])
    dict_b = dict(b=[3], c=[4])
    complete_merge = merge_dicts(dict_a, dict_b, True)
    print(complete_merge)
    resolved_merge = merge_dicts(dict_a, dict_b, False)
    print(resolved_merge)


def merge_dicts(a, b, complete):
    new_dict = copy.deepcopy(a)
    if complete:
        for key, value in b.items():
            new_dict.setdefault(key, []).extend(value)
    else:
        for key, value in b.items():
            if key in new_dict:
                # rename first key
                counter = itertools.count(1)
                while True:
                    new_key = f'{key}_{next(counter)}'
                    if new_key not in new_dict:
                        new_dict[new_key] = new_dict.pop(key)
                        break
                # create second key
                while True:
                    new_key = f'{key}_{next(counter)}'
                    if new_key not in new_dict:
                        new_dict[new_key] = value
                        break
            else:
                new_dict[key] = value
    return new_dict


if __name__ == '__main__':
    main()

程序显示两个合并词典的以下表示形式:

{'a': [1], 'b': [2, 3], 'c': [4]}
{'a': [1], 'b_1': [2], 'b_2': [3], 'c': [4]}

答案 1 :(得分:3)

我想你想要这个:

dict1 = {'a':[1], 'b':[2]}
dict2 = {'b':[3], 'c':[4]}

def mergeArray(conflict):
    for key in dict1.keys():
        if dict2.has_key(key):
            if conflict==False:
                dict2[key].extend(dict1[key])
            else:
                dict2[key+'_1'] = dict1[key]
                dict2[key+'_2'] = dict2.pop(key)
        else:
            dict2[key] = dict1[key]

mergeArray(True);
print dict2
相关问题