How to merge dictionaries of dictionaries?

后端 未结 29 2777
渐次进展
渐次进展 2020-11-22 05:13

I need to merge multiple dictionaries, here\'s what I have for instance:

dict1 = {1:{\"a\":{A}}, 2:{\"b\":{B}}}

dict2 = {2:{\"c\":{C}}, 3:{\"d\":{D}}
         


        
29条回答
  •  攒了一身酷
    2020-11-22 06:04

    How about another answer?!? This one also avoids mutation/side effects:

    def merge(dict1, dict2):
        output = {}
    
        # adds keys from `dict1` if they do not exist in `dict2` and vice-versa
        intersection = {**dict2, **dict1}
    
        for k_intersect, v_intersect in intersection.items():
            if k_intersect not in dict1:
                v_dict2 = dict2[k_intersect]
                output[k_intersect] = v_dict2
    
            elif k_intersect not in dict2:
                output[k_intersect] = v_intersect
    
            elif isinstance(v_intersect, dict):
                v_dict2 = dict2[k_intersect]
                output[k_intersect] = merge(v_intersect, v_dict2)
    
            else:
                output[k_intersect] = v_intersect
    
        return output
    
    
    dict1 = {1:{"a":{"A"}}, 2:{"b":{"B"}}}
    dict2 = {2:{"c":{"C"}}, 3:{"d":{"D"}}}
    dict3 = {1:{"a":{"A"}}, 2:{"b":{"B"},"c":{"C"}}, 3:{"d":{"D"}}}
    
    assert dict3 == merge(dict1, dict2)
    

提交回复
热议问题