'Cumulatively add values to python dictionary

Suppose ,I have a dictionary

key={'a':5}

Now ,I want to add values to it cumulatively without overwriting the current value but adding on to it.How to do it? I am giving an instance:

for post in doc['post']:
    if 'wow' in post:
        value=2
        for reactor in post['wow']['reactors']:
            dict_of_reactor_ids.update({reactor['img_id']:value})
    if  'sad' in post:
        value=2
        for reactor in post['sad']['reactors']:
            dict_of_reactor_ids.update({reactor['img_id']:value})

Suppose if the dictionary is like this in first iteration

dict_of_reactor_ids={101:2,102:1}

and NOW I want to increase the value of 101 key by 3 ,then how to do that.

dict_of_reactor_ids={101:5,102:1}

Now in second iteration of post ,I want to add values to the current values in dictionary without overwriting the current value.
I have tried update method but I think it just updates the whole value instead of adding onto it.



Solution 1:[1]

Sounds like a typical case of Counter:

>>> from collections import Counter
>>> c = Counter()
>>> c["a"] += 1 # works even though "a" is not yet present
>>> c.update({"a": 2, "b": 2}) # possible to do multiple updates
{"a": 3, "b": 2}

In your case the benefit is that it works even when the key is not already in there (default value is 0), and it allows updates of multiple values at once, whereas update on a normal dict would overwrite the value as you've noticed.

Solution 2:[2]

You can also use defaultdict, it "defaults" when there is not yet an existing key-value pair and you still use the cumulative add +=:

from collections import defaultdict

dict_of_reactor_ids = defaultdict(int)
dict_of_reactor_ids[101] += 2
dict_of_reactor_ids[102] += 1
dict_of_reactor_ids['101'] += 3
print(dict_of_reactor_ids['101'])
5

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 PascalVKooten
Solution 2 questionto42standswithUkraine