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

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

    A more generic solution, which works for non-numeric values as well:

    a = {'a': 'foo', 'b':'bar', 'c': 'baz'}
    b = {'a': 'spam', 'c':'ham', 'x': 'blah'}
    
    r = dict(a.items() + b.items() +
        [(k, a[k] + b[k]) for k in set(b) & set(a)])
    

    or even more generic:

    def combine_dicts(a, b, op=operator.add):
        return dict(a.items() + b.items() +
            [(k, op(a[k], b[k])) for k in set(b) & set(a)])
    

    For example:

    >>> a = {'a': 2, 'b':3, 'c':4}
    >>> b = {'a': 5, 'c':6, 'x':7}
    
    >>> import operator
    >>> print combine_dicts(a, b, operator.mul)
    {'a': 10, 'x': 7, 'c': 24, 'b': 3}
    

提交回复
热议问题