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

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

    This solution is easy to use, it is used as a normal dictionary, but you can use the sum function.

    class SumDict(dict):
        def __add__(self, y):
            return {x: self.get(x, 0) + y.get(x, 0) for x in set(self).union(y)}
    
    A = SumDict({'a': 1, 'c': 2})
    B = SumDict({'b': 3, 'c': 4})  # Also works: B = {'b': 3, 'c': 4}
    print(A + B)  # OUTPUT {'a': 1, 'b': 3, 'c': 6}
    

提交回复
热议问题