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))] )
solving not in terms of "length" but performance, I'd do the following:
it's also py3k-compatible, unlike your original code.
Comment for @John Pirie's answer:
Here's implementation that doesn't use
(self.keys() + rhs.keys())
:If you want short code, you're there.
If you want clean code, inherit from Ber's
defaultdict
and overload__add__
:Gives:
In my first impression, I will write:
Easiest to just use a
Counter
The first thing I think of is a bit more efficient and (IMO) a bit more elegant, but still too much typing. Actually, it's about equivalent to kcwu's.
It's really a shame that
dict.update
doesn't returnself
. I guess it's not the Python way. If it did, the[..., d][1]
trick would be unnecessary.