0

I have dictionary which contains dictionary as value for it's keys. I want to create a single dictionary out of it and also if there are keys repeating it should add the values of those keys

So I have

temp_dict = {0: {'a':1, 'b':2}, 1: {'c':3,'d':4}, 2: {'d':5,'e':6}}

I tried this for making it a single dictionary (not adding the values from same keys in this step though)

empty_dict = {}
for d in empty_dict:
    for k,v in d.items():
        empty_dict[k] = v

But the above code is also showing error. And then the next step is too add the values from same key.

I expect the output as

new_dict = {'a':1, 'b':2, 'c':3, 'd':9, 'e':6}

d has 9 by adding values from the both the 'd's above.

1 Answers1

0

You can use Counter from the stdlib

from collections import Counter

c = Counter()

for i in temp_dict.values():
    c.update(i)

Counter({'a': 1, 'b': 2, 'c': 3, 'd': 9, 'e': 6})
gold_cy
  • 13,648
  • 3
  • 23
  • 45