Skip to content

Python sum dictionary values by key | Example code

  • by

Use the 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

A simple example code has two dictionaries with the same keys and different numeric values. We are merging these dictionaries into one and summing 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

To sum dictionary values by key in Python, you can use a loop to iterate through the dictionary and accumulate the values for each key. Here’s a simple example of how to do this:

# Sample dictionary
data = {
    'a': 10,
    'b': 20,
    'a': 5,
    'c': 15,
    'b': 25,
    'd': 30
}

# Create an empty dictionary to store the sums
sums = {}

# Iterate through the original dictionary
for key, value in data.items():
    if key in sums:
        sums[key] += value
    else:
        sums[key] = value

print(sums)

Please note that this code sums the values for duplicate keys in the original dictionary. If you want to preserve the original dictionary and create a new dictionary with the sums, you can use a defaultdict from the collections module:

from collections import defaultdict

data = {
    'a': 10,
    'b': 20,
    'a': 5,
    'c': 15,
    'b': 25,
    'd': 30
}

# Create a defaultdict with int as the default factory
sums = defaultdict(int)

# Iterate through the original dictionary and add values to the sums
for key, value in data.items():
    sums[key] += value

# Convert the defaultdict to a regular dictionary if needed
sums = dict(sums)

print(sums)

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

Note: IDE: PyCharm 2021.3.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 *