How to merge dictionaries of dictionaries?

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

    The following function merges b into a.

    def mergedicts(a, b):
        for key in b:
            if isinstance(a.get(key), dict) or isinstance(b.get(key), dict):
                mergedicts(a[key], b[key])
            else:
                a[key] = b[key]
        return a
    

提交回复
热议问题