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

前端 未结 17 2552
梦毁少年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:50

    From python 3.5: merging and summing

    Thanks to @tokeinizer_fsj that told me in a comment that I didn't get completely the meaning of the question (I thought that add meant just adding keys that eventually where different in the two dictinaries and, instead, i meant that the common key values should be summed). So I added that loop before the merging, so that the second dictionary contains the sum of the common keys. The last dictionary will be the one whose values will last in the new dictionary that is the result of the merging of the two, so I thing the problem is solved. The solution is valid from python 3.5 and following versions.

    a = {
        "a": 1,
        "b": 2,
        "c": 3
    }
    
    b = {
        "a": 2,
        "b": 3,
        "d": 5
    }
    
    # Python 3.5
    
    for key in b:
        if key in a:
            b[key] = b[key] + a[key]
    
    c = {**a, **b}
    print(c)
    
    >>> c
    {'a': 3, 'b': 5, 'c': 3, 'd': 5}
    

    Reusable code

    a = {'a': 1, 'b': 2, 'c': 3}
    b = {'b': 3, 'c': 4, 'd': 5}
    
    
    def mergsum(a, b):
        for k in b:
            if k in a:
                b[k] = b[k] + a[k]
        c = {**a, **b}
        return c
    
    
    print(mergsum(a, b))
    

提交回复
热议问题