How to merge dictionaries of dictionaries?

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

    In case someone wants yet another approach to this problem, here's my solution.

    Virtues: short, declarative, and functional in style (recursive, does no mutation).

    Potential Drawback: This might not be the merge you're looking for. Consult the docstring for semantics.

    def deep_merge(a, b):
        """
        Merge two values, with `b` taking precedence over `a`.
    
        Semantics:
        - If either `a` or `b` is not a dictionary, `a` will be returned only if
          `b` is `None`. Otherwise `b` will be returned.
        - If both values are dictionaries, they are merged as follows:
            * Each key that is found only in `a` or only in `b` will be included in
              the output collection with its value intact.
            * For any key in common between `a` and `b`, the corresponding values
              will be merged with the same semantics.
        """
        if not isinstance(a, dict) or not isinstance(b, dict):
            return a if b is None else b
        else:
            # If we're here, both a and b must be dictionaries or subtypes thereof.
    
            # Compute set of all keys in both dictionaries.
            keys = set(a.keys()) | set(b.keys())
    
            # Build output dictionary, merging recursively values with common keys,
            # where `None` is used to mean the absence of a value.
            return {
                key: deep_merge(a.get(key), b.get(key))
                for key in keys
            }
    

提交回复
热议问题