Python dictionary update values and elements in each iteration

I have a main dictionary named summary.

summary = {}

And I have another dictionary ‘temp’ that is generated with different key value pairs in each iteration of a loop.

For example:
In first iteration of loop,

temp = {'a': 10, 'b': 50}

In second iteration of loop,

temp = {'a': 40, 'b': 20, 'c'=100}

I want the main dictionary summary to be updated after each iteration with the elements of temp. If a key IS NOT already present in summary, the key-value pair from temp should be entered into it. If a key IS already present in ‘summary’, then the value needs to be added to the existing value for that key in ‘summary’.

So my desired result here after 2 iterations is,

summary = {'a': 50, 'b': 70, 'c'=100}

I tried to use update function, but it was not working

>Solution :

Using dict.update here isn’t going to give you your desired results, because that completely overrides values in the dictionary. What you want to do is add the values to the existing key-value pairs in the summary at the end of each loop iteration.

I would use a defaultdict for the summary such that you can easily add to it from each temp dict created without having to explicitly initialize the key to 0. At the end of each iteration, take the entries from each temp dict and add them one at a time to the summary.

Example:

from collections import defaultdict

temp_dicts = [{'a': 10, 'b': 50}, {'a': 40, 'b': 20, 'c': 100}]

summary = defaultdict(int)

for temp in temp_dicts:
    for key, value in temp.items():
        summary[key] += value

print(dict(summary))

Outputs:

{'a': 50, 'b': 70, 'c': 100}

You could also achieve a similar result with a Counter, which supports keeping track of the counts for keys. Using the | operator you can append directly from the temp dicts

from collections import Counter

temp_dicts = [{'a': 10, 'b': 50}, {'a': 40, 'b': 20, 'c': 100}]

summary = Counter()

for temp in temp_dicts:
    summary |= temp

print(dict(summary))

Leave a Reply