0

I have many dicts, I'm giving 2 for this example:

dict1={'green': 3, 'yellow': 5, 'blue': 1}
dict2={'green': 5, 'yellow': 1, 'blue': 3, 'purple': 10}

I've been trying to find a way to add the 2 dicts so i can have updated values(sum) for existing keys, and added up keys and values for non-existant ones.

Results:

results = {'green': 8, 'yellow': 6, 'blue': 4, 'purple': 10}

I tried dict1.update(dict2) but as you know , I've only got a dictionary with updated values, not summed up.

Any ways to achieve this?

UPDATE:

Solved : Actually collections.Counter did the trick ... Thanks

The Other Guy
  • 576
  • 10
  • 21

2 Answers2

0
{x: dict1.get(x,0) + dict2.get(x,0) for x in set(dict1.keys() + dict2.keys())}

Output:

{'blue': 4, 'purple': 10, 'green': 8, 'yellow': 6}
Kevin
  • 74,910
  • 12
  • 133
  • 166
0

Huh, that's surprisingly hard...

dicts = [dict1, dict2]
dict([(key, sum(map(lambda x: x.get(key) or 0, dicts))) for key in set(reduce(lambda a,b: a + b, map(lambda x: x.keys(), dicts), []))])

[{'blue': 1, 'green': 3, 'yellow': 5}, {'blue': 3, 'purple': 10, 'green': 5, 'yellow': 1}]

Or more readable

dicts = [dict1, dict2]
keys = reduce(lambda a,b: a + b, map(lambda x: x.keys(), dicts), [])
dict([(key, sum(map(lambda x: x.get(key) or 0, dicts))) for key in set(keys)])