How to merge dictionaries of dictionaries?

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

    I've been testing your solutions and decided to use this one in my project:

    def mergedicts(dict1, dict2, conflict, no_conflict):
        for k in set(dict1.keys()).union(dict2.keys()):
            if k in dict1 and k in dict2:
                yield (k, conflict(dict1[k], dict2[k]))
            elif k in dict1:
                yield (k, no_conflict(dict1[k]))
            else:
                yield (k, no_conflict(dict2[k]))
    
    dict1 = {1:{"a":"A"}, 2:{"b":"B"}}
    dict2 = {2:{"c":"C"}, 3:{"d":"D"}}
    
    #this helper function allows for recursion and the use of reduce
    def f2(x, y):
        return dict(mergedicts(x, y, f2, lambda x: x))
    
    print dict(mergedicts(dict1, dict2, f2, lambda x: x))
    print dict(reduce(f2, [dict1, dict2]))
    

    Passing functions as parameteres is key to extend jterrace solution to behave as all the other recursive solutions.

提交回复
热议问题