Python sum dictionary values by key | Example code

  • by

Use Collection module counter function to sum dictionary values by key in Python. The counter is a sub-class that is used to count hashable objects and count each of the elements present in the container.

Example sum dictionary values by key in Python

Simple example code has two dictionaries with the same keys and different numeric values. We are merging these dictionaries into one and sum the dictionary values by key.

from collections import Counter

x = {"a": 200, "b": 560, "y": 2005, "z": 2555}
y = {"a": 255, "b": 266, "y": 3050, "z": 3033}

z = Counter(x) + Counter(y)

print(z)

Output:

Python sum dictionary values by key

For example, if you want to add all the values of a dictionary together to find the sum. Call dict.values() to return the values of a dictionary dict then use sum(values) to return the sum of the values.

a_dict = {"a": 1, "b": 2, "c": 3}

values = a_dict.values()

total = sum(values)
print(total)

Output: 6

Do comment if you have any doubts or suggestions on this Python sum topic.

Note: IDE: PyCharm 2021.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.