KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
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))] )
Tags (comma-separated)
Save Edits
Cancel