Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
668 views
in Technique[技术] by (71.8m points)

code golf - python dict.add_by_value(dict_2)?

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))] )
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Easiest to just use a Counter

>>> from collections import Counter
>>> a = dict(a=1,b=2    )
>>> b = dict(    b=3,c=2)
>>> Counter(a)+Counter(b)
Counter({'b': 5, 'c': 2, 'a': 1})
>>> dict(Counter({'b': 5, 'c': 2, 'a': 1}))
{'a': 1, 'c': 2, 'b': 5}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...