python dict.add_by_value(dict_2)?

2019-01-09 15:37发布

The problem:

>>> a = dict(a=1,b=2    )
>>> b = dict(    b=3,c=2)

>>> c = ???

c = {'a': 1, 'b': 5, 'c': 2}

So, the idea is two add to dictionaries by int/float values in the shortest form. Here's one solution that I've devised, but I don't like it, cause it's long:

c = dict([(i,a.get(i,0) + b.get(i,0)) for i in set(a.keys()+b.keys())])

I think there must be a shorter/concise solution (maybe something to do with reduce and operator module? itertools?)... Any ideas?


Update: I'm really hoping to find something more elegant like "reduce(operator.add, key = itemgetter(0), a+b)". (Obviously that isn't real code, but you should get the idea). But it seems that may be a dream.


Update: Still loking for more concise solutions. Maybe groupby can help? The solution I've come up with using "reduce"/"groupby" isn't actually concise:

from itertools import groupby
from operator import itemgetter,add

c = dict( [(i,reduce(add,map(itemgetter(1), v))) \
              for i,v in groupby(sorted(a.items()+b.items()), itemgetter(0))] )

8条回答
劳资没心,怎么记你
2楼-- · 2019-01-09 16:08
def GenerateSum():
  for k in set(a).union(b):
    yield k, a.get(k, 0) + b.get(k, 0)

e = dict(GenerateSum())
print e

or, with a one liner:

 print dict((k, a.get(k,0) + b.get(k,0)) for k in set(a).union(b))
查看更多
做个烂人
3楼-- · 2019-01-09 16:13

I think one line of code is already pretty short :)

I may become "half a line", it you use defaultdict and remove some unnecessary list and set creations:

from collections import defaultdict

a = defaultdict(int, a=1, b=2)
b = defaultdict(int, b=3, c=4)

c = dict((k, a[k]+b[k]) for k in (a.keys() + b.keys()))
print c
查看更多
登录 后发表回答