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

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

    Use collections.Counter:

    >>> from collections import Counter
    >>> A = Counter({'a':1, 'b':2, 'c':3})
    >>> B = Counter({'b':3, 'c':4, 'd':5})
    >>> A + B
    Counter({'c': 7, 'b': 5, 'd': 5, 'a': 1})
    

    Counters are basically a subclass of dict, so you can still do everything else with them you'd normally do with that type, such as iterate over their keys and values.

提交回复
热议问题