Skip to content

Python sum list of dictionary values | Example code

  • by

Use sum() and values() functions to sum a list of dictionary values dictionary in Python. But before that, you have to combine all the same keys add those keys’ values, and make one dictionary.

Example sum list of dictionary values in Python

A simple example code sum up all the same key values into one in the dictionary. Accumulate the sum for the respective key using a for loop.

original_list = [
    {'A': 1, 'B': 7, 'B': 5, 'C': 2, 'D': 5, 'E': 3, 'F': 9, 'G': 6, 'H': 4, 'X': 8},
    {'A': 2, 'B': 7, 'B': 5, 'C': 2, 'D': 5, 'E': 3, 'F': 9, 'G': 6, 'H': 4, 'X': 8},
    {'A': 1, 'B': 7, 'B': 5, 'C': 2, 'D': 5, 'E': 3, 'F': 9, 'G': 6, 'H': 4, 'X': 8},
]

result = {}
for elm in original_list:
    for k, v in elm.items():

        # Initialise it if it doesn't exist
        if k not in result:
            result[k] = 0

        # accumulate sum seperately
        result[k] += v

print(result)

Output:

Python sum list of dictionary values

And if you want all values sump, use values() function and sum() function. Where dict.values() to return the values of a dictionary dict and sum(values) to return the sum of the values

original_list = [
    {'A': 1, 'B': 7, 'B': 5, 'C': 2, 'D': 5, 'E': 3, 'F': 9, 'G': 6, 'H': 4, 'X': 8},
    {'A': 2, 'B': 7, 'B': 5, 'C': 2, 'D': 5, 'E': 3, 'F': 9, 'G': 6, 'H': 4, 'X': 8},
    {'A': 1, 'B': 7, 'B': 5, 'C': 2, 'D': 5, 'E': 3, 'F': 9, 'G': 6, 'H': 4, 'X': 8},
]

result = {}
for elm in original_list:
    for k, v in elm.items():

        # Initialise it if it doesn't exist
        if k not in result:
            result[k] = 0

        # accumulate sum seperately
        result[k] += v

value = result.values()

print(sum(value))

Output: 130

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

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading