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

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

本文介绍了如何合并两个具有相同键名的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to Python and am trying to write a function that will merge two dictionary objects in python.For instance

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

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

I need to produce a new merged dictionary

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

函数还应该带有一个参数"conflict"(设置为True或False).当将冲突设置为False时,上面的方法就可以了.当将冲突设置为True时,代码将像这样合并字典:

Function should also take a parameter "conflict" (set to True or False). When conflict is set to False, above is fine. When conflict is set to True, code will merge the dictionary like this instead:

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

我正在尝试附加这两个字典,但不确定如何正确使用它.

I am trying to append the 2 dictionaries, but not sure how to do it the right way.

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

推荐答案

如果您希望合并的副本不更改原始字典并监视名称冲突,则可能需要尝试以下解决方案:

If you want a merged copy that does not alter the original dicts and watches for name conflicts, you might want to try this solution:

#! /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()

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

The program displays the following representation for the two merged dictionaries:

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

这篇关于如何合并两个具有相同键名的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 08:11