How to merge dictionaries of dictionaries?

后端 未结 29 3154
渐次进展
渐次进展 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 05:52

    The code will depend on your rules for resolving merge conflicts, of course. Here's a version which can take an arbitrary number of arguments and merges them recursively to an arbitrary depth, without using any object mutation. It uses the following rules to resolve merge conflicts:

    • dictionaries take precedence over non-dict values ({"foo": {...}} takes precedence over {"foo": "bar"})
    • later arguments take precedence over earlier arguments (if you merge {"a": 1}, {"a", 2}, and {"a": 3} in order, the result will be {"a": 3})
    try:
        from collections import Mapping
    except ImportError:
        Mapping = dict
    
    def merge_dicts(*dicts):                                                            
        """                                                                             
        Return a new dictionary that is the result of merging the arguments together.   
        In case of conflicts, later arguments take precedence over earlier arguments.   
        """                                                                             
        updated = {}                                                                    
        # grab all keys                                                                 
        keys = set()                                                                    
        for d in dicts:                                                                 
            keys = keys.union(set(d))                                                   
    
        for key in keys:                                                                
            values = [d[key] for d in dicts if key in d]                                
            # which ones are mapping types? (aka dict)                                  
            maps = [value for value in values if isinstance(value, Mapping)]            
            if maps:                                                                    
                # if we have any mapping types, call recursively to merge them          
                updated[key] = merge_dicts(*maps)                                       
            else:                                                                       
                # otherwise, just grab the last value we have, since later arguments    
                # take precedence over earlier arguments                                
                updated[key] = values[-1]                                               
        return updated  
    

提交回复
热议问题