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

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

    For a more generic and extensible way check mergedict. It uses singledispatch and can merge values based on its types.

    Example:

    from mergedict import MergeDict
    
    class SumDict(MergeDict):
        @MergeDict.dispatch(int)
        def merge_int(this, other):
            return this + other
    
    d2 = SumDict({'a': 1, 'b': 'one'})
    d2.merge({'a':2, 'b': 'two'})
    
    assert d2 == {'a': 3, 'b': 'two'}
    

提交回复
热议问题