Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

前端 未结 17 2345
梦毁少年i
梦毁少年i 2020-11-22 01:50

For example I have two dicts:

Dict A: {\'a\': 1, \'b\': 2, \'c\': 3}
Dict B: {\'b\': 3, \'c\': 4, \'d\': 5}

I need a pythonic way of \'comb

17条回答
  •  抹茶落季
    2020-11-22 02:57

    This is a simple solution for merging two dictionaries where += can be applied to the values, it has to iterate over a dictionary only once

    a = {'a':1, 'b':2, 'c':3}
    
    dicts = [{'b':3, 'c':4, 'd':5},
             {'c':9, 'a':9, 'd':9}]
    
    def merge_dicts(merged,mergedfrom):
        for k,v in mergedfrom.items():
            if k in merged:
                merged[k] += v
            else:
                merged[k] = v
        return merged
    
    for dct in dicts:
        a = merge_dicts(a,dct)
    print (a)
    #{'c': 16, 'b': 5, 'd': 14, 'a': 10}
    

提交回复
热议问题