How to merge dictionaries of dictionaries?

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

    This should help in merging all items from dict2 into dict1:

    for item in dict2:
        if item in dict1:
            for leaf in dict2[item]:
                dict1[item][leaf] = dict2[item][leaf]
        else:
            dict1[item] = dict2[item]
    

    Please test it and tell us whether this is what you wanted.

    EDIT:

    The above mentioned solution merges only one level, but correctly solves the example given by OP. To merge multiple levels, the recursion should be used.

提交回复
热议问题