How to merge dictionaries of dictionaries?

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

    Based on answers from @andrew cooke. It takes care of nested lists in a better way.

    def deep_merge_lists(original, incoming):
        """
        Deep merge two lists. Modifies original.
        Recursively call deep merge on each correlated element of list. 
        If item type in both elements are
         a. dict: Call deep_merge_dicts on both values.
         b. list: Recursively call deep_merge_lists on both values.
         c. any other type: Value is overridden.
         d. conflicting types: Value is overridden.
    
        If length of incoming list is more that of original then extra values are appended.
        """
        common_length = min(len(original), len(incoming))
        for idx in range(common_length):
            if isinstance(original[idx], dict) and isinstance(incoming[idx], dict):
                deep_merge_dicts(original[idx], incoming[idx])
    
            elif isinstance(original[idx], list) and isinstance(incoming[idx], list):
                deep_merge_lists(original[idx], incoming[idx])
    
            else:
                original[idx] = incoming[idx]
    
        for idx in range(common_length, len(incoming)):
            original.append(incoming[idx])
    
    
    def deep_merge_dicts(original, incoming):
        """
        Deep merge two dictionaries. Modifies original.
        For key conflicts if both values are:
         a. dict: Recursively call deep_merge_dicts on both values.
         b. list: Call deep_merge_lists on both values.
         c. any other type: Value is overridden.
         d. conflicting types: Value is overridden.
    
        """
        for key in incoming:
            if key in original:
                if isinstance(original[key], dict) and isinstance(incoming[key], dict):
                    deep_merge_dicts(original[key], incoming[key])
    
                elif isinstance(original[key], list) and isinstance(incoming[key], list):
                    deep_merge_lists(original[key], incoming[key])
    
                else:
                    original[key] = incoming[key]
            else:
                original[key] = incoming[key]
    

提交回复
热议问题