How to merge dictionaries of dictionaries?

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

    Since dictviews support set operations, I was able to greatly simplify jterrace's answer.

    def merge(dict1, dict2):
        for k in dict1.keys() - dict2.keys():
            yield (k, dict1[k])
    
        for k in dict2.keys() - dict1.keys():
            yield (k, dict2[k])
    
        for k in dict1.keys() & dict2.keys():
            yield (k, dict(merge(dict1[k], dict2[k])))
    

    Any attempt to combine a dict with a non dict (technically, an object with a 'keys' method and an object without a 'keys' method) will raise an AttributeError. This includes both the initial call to the function and recursive calls. This is exactly what I wanted so I left it. You could easily catch an AttributeErrors thrown by the recursive call and then yield any value you please.

提交回复
热议问题