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

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

    def merge_with(f, xs, ys):
        xs = a_copy_of(xs) # dict(xs), maybe generalizable?
        for (y, v) in ys.iteritems():
            xs[y] = v if y not in xs else f(xs[x], v)
    
    merge_with((lambda x, y: x + y), A, B)
    

    You could easily generalize this:

    def merge_dicts(f, *dicts):
        result = {}
        for d in dicts:
            for (k, v) in d.iteritems():
                result[k] = v if k not in result else f(result[k], v)
    

    Then it can take any number of dicts.

提交回复
热议问题