How to merge dictionaries of dictionaries?

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

    This simple recursive procedure will merge one dictionary into another while overriding conflicting keys:

    #!/usr/bin/env python2.7
    
    def merge_dicts(dict1, dict2):
        """ Recursively merges dict2 into dict1 """
        if not isinstance(dict1, dict) or not isinstance(dict2, dict):
            return dict2
        for k in dict2:
            if k in dict1:
                dict1[k] = merge_dicts(dict1[k], dict2[k])
            else:
                dict1[k] = dict2[k]
        return dict1
    
    print (merge_dicts({1:{"a":"A"}, 2:{"b":"B"}}, {2:{"c":"C"}, 3:{"d":"D"}}))
    print (merge_dicts({1:{"a":"A"}, 2:{"b":"B"}}, {1:{"a":"A"}, 2:{"b":"C"}}))
    

    Output:

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

提交回复
热议问题