How to merge dictionaries of dictionaries?

后端 未结 29 2742
渐次进展
渐次进展 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:15

    Easiest way i can think of is :

    #!/usr/bin/python
    
    from copy import deepcopy
    def dict_merge(a, b):
        if not isinstance(b, dict):
            return b
        result = deepcopy(a)
        for k, v in b.iteritems():
            if k in result and isinstance(result[k], dict):
                    result[k] = dict_merge(result[k], v)
            else:
                result[k] = deepcopy(v)
        return result
    
    a = {1:{"a":'A'}, 2:{"b":'B'}}
    b = {2:{"c":'C'}, 3:{"d":'D'}}
    
    print dict_merge(a,b)
    

    Output:

    {1: {'a': 'A'}, 2: {'c': 'C', 'b': 'B'}, 3: {'d': 'D'}}
    

提交回复
热议问题