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

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

    >>> A = {'a':1, 'b':2, 'c':3}
    >>> B = {'b':3, 'c':4, 'd':5}
    >>> c = {x: A.get(x, 0) + B.get(x, 0) for x in set(A).union(B)}
    >>> print(c)
    
    {'a': 1, 'c': 7, 'b': 5, 'd': 5}
    

提交回复
热议问题