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

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

    import itertools
    import collections
    
    dictA = {'a':1, 'b':2, 'c':3}
    dictB = {'b':3, 'c':4, 'd':5}
    
    new_dict = collections.defaultdict(int)
    # use dict.items() instead of dict.iteritems() for Python3
    for k, v in itertools.chain(dictA.iteritems(), dictB.iteritems()):
        new_dict[k] += v
    
    print dict(new_dict)
    
    # OUTPUT
    {'a': 1, 'c': 7, 'b': 5, 'd': 5}
    

    OR

    Alternative you can use Counter as @Martijn has mentioned above.

提交回复
热议问题