How to merge dictionaries of dictionaries?

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

    I have another slightly different solution here:

    def deepMerge(d1, d2, inconflict = lambda v1,v2 : v2) :
    ''' merge d2 into d1. using inconflict function to resolve the leaf conflicts '''
        for k in d2:
            if k in d1 : 
                if isinstance(d1[k], dict) and isinstance(d2[k], dict) :
                    deepMerge(d1[k], d2[k], inconflict)
                elif d1[k] != d2[k] :
                    d1[k] = inconflict(d1[k], d2[k])
            else :
                d1[k] = d2[k]
        return d1
    

    By default it resolves conflicts in favor of values from the second dict, but you can easily override this, with some witchery you may be able to even throw exceptions out of it. :).

提交回复
热议问题