How to merge multiple dicts with same key?

前端 未结 14 2539
别跟我提以往
别跟我提以往 2020-11-22 13:12

I have multiple dicts/key-value pairs like this:

d1 = {key1: x1, key2: y1}  
d2 = {key1: x2, key2: y2}  

I want the result to be a new di

14条回答
  •  误落风尘
    2020-11-22 13:39

    This library helped me, I had a dict list of nested keys with the same name but with different values, every other solution kept overriding those nested keys.

    https://pypi.org/project/deepmerge/

    from deepmerge import always_merger
    
    def process_parms(args):
        temp_list = []
        for x in args:
            with open(x, 'r') as stream:
                temp_list.append(yaml.safe_load(stream))
    
        return always_merger.merge(*temp_list)
    

提交回复
热议问题