Skip to content Skip to sidebar Skip to footer

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 instan

Solution 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.

Post a Comment for "Cumulatively Add Values To Python Dictionary"