Sum all values in a Dictionary or List of Dicts in Python

avatar
Borislav Hadzhiev

Last updated: Apr 9, 2024
5 min

banner

# Table of Contents

  1. Sum all values in a dictionary in Python
  2. Sum all values in a dictionary using a for loop
  3. Sum all values in a dictionary using reduce()
  4. Sum the values in a List of Dictionaries in Python

# Sum all values in a dictionary in Python

Use the sum() function to sum all values in a dictionary.

The values() method on the dictionary will return a view of the dictionary's values, which can directly be passed to the sum() function to get the sum.

main.py
my_dict = { 'one': 1, 'two': 2, 'three': 3, } total = sum(my_dict.values()) print(total) # ๐Ÿ‘‰๏ธ 6 # ๐Ÿ‘‡๏ธ [1, 2, 3] print(list(my_dict.values()))

sum all values in dictionary

The code for this article is available on GitHub

We used the sum() function to sum all values in a dictionary.

The dict.values() method returns a new view of the dictionary's values.

The sum() function takes an iterable, sums its items from left to right and returns the total.

main.py
print(sum([1, 2, 3])) # ๐Ÿ‘‰๏ธ 6

The sum function takes the following 2 arguments:

NameDescription
iterablethe iterable whose items to sum
startsums the start value and the items of the iterable. sum defaults to 0 (optional)

Notice that the value for the optional start argument defaults to 0. This means that using this approach with an empty dictionary would return 0.

main.py
my_dict = {} total = sum(my_dict.values()) print(total) # ๐Ÿ‘‰๏ธ 0 # ๐Ÿ‘‡๏ธ [] print(list(my_dict.values()))

Alternatively, you can use a for loop.

# Sum all values in a dictionary using a for loop

This is a three-step process:

  1. Declare a new variable and initialize it to 0.
  2. Use a for loop to iterate over the dictionary's values.
  3. On each iteration, add the current dictionary value to the variable.
main.py
my_dict = { 'one': 1, 'two': 2, 'three': 3, } total = 0 for value in my_dict.values(): total += value print(total) # ๐Ÿ‘‰๏ธ 6

sum all values in dictionary using for loop

The code for this article is available on GitHub

We initialized the total variable to 0 and used the dict.values() method to get an iterator of the dictionary's values.

On each iteration, we reassign the total variable to the result of adding the current value to it.

# Sum all values in a dictionary using reduce()

You can also sum all values in a dictionary using the reduce() function.

main.py
from functools import reduce my_dict = { 'one': 1, 'two': 2, 'three': 3, } total = reduce( lambda acc, current: acc + current, my_dict.values() ) print(total) # ๐Ÿ‘‰๏ธ 6
The code for this article is available on GitHub

Using the reduce() function is definitely not needed in this scenario as it is much more verbose than passing the view of the dictionary's values directly to the sum() function.

The reduce() function takes the following 3 parameters:

NameDescription
functionA function that takes 2 parameters - the accumulated value and a value from the iterable.
iterableEach element in the iterable will get passed as an argument to the function.
initializerAn optional initializer value that is placed before the items of the iterable in the calculation.
The lambda function in the example takes the accumulated value and the current value as parameters and returns the sum of the two.

If we provide a value for the initializer argument, it is placed before the items of the iterable in the calculation.

main.py
from functools import reduce my_dict = { 'one': 1, 'two': 2, 'three': 3, } total = reduce( lambda acc, current: acc + current, my_dict.values(), 0 ) print(total) # ๐Ÿ‘‰๏ธ 6

In the example, we passed 0 for the initializer argument, so the value of the accumulator will be 0 on the first iteration.

The value of the accumulator would get set to the first element in the iterable if we didn't pass a value for the initializer.

If the iterable is empty and the initializer is provided, the initializer is returned.

main.py
from functools import reduce my_dict = {} total = reduce( lambda acc, current: acc + current, my_dict.values(), 0 ) print(total) # ๐Ÿ‘‰๏ธ 0

# Sum the values in a list of dictionaries in Python

To sum the values in a list of dictionaries:

  1. Use a generator expression to iterate over the list.
  2. On each iteration, access the current dictionary at the specific key.
  3. Pass the generator expression to the sum() function.
main.py
from collections import Counter # โœ… Sum the values in a list of dictionaries for a specific `dict` key list_of_dicts = [ {'name': 'Alice', 'salary': 100}, {'name': 'Bob', 'salary': 100}, {'name': 'Carl', 'salary': 100}, ] total = sum(d['salary'] for d in list_of_dicts) print(total) # ๐Ÿ‘‰๏ธ 300
The code for this article is available on GitHub

We used a generator expression to iterate over the list of dictionaries.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we access the specific dict key to get the corresponding value and return the result.

The sum() function takes an iterable, sums its items from left to right and returns the total.

The sum function takes the following 2 arguments:

NameDescription
iterablethe iterable whose items to sum
startsums the start value and the items of the iterable. sum defaults to 0 (optional)

# Sum the values in a list of dictionaries for All dictionary keys

If you need to sum the values in a list of dictionaries for all dictionary keys, use the Counter class.

main.py
from collections import Counter list_of_dicts = [ {'id': 1, 'salary': 100}, {'id': 2, 'salary': 100}, {'id': 3, 'salary': 100}, ] my_dict = Counter() for d in list_of_dicts: for key, value in d.items(): my_dict[key] += value # ๐Ÿ‘‡๏ธ Counter({'salary': 300, 'id': 6}) print(my_dict) total = sum(my_dict.values()) print(total) # ๐Ÿ‘‰๏ธ 306
The code for this article is available on GitHub

The Counter class from the collections module is a subclass of the dict class.

The class is basically a mapping of key-count pairs.

The values are allowed to be any integer (including zero and negative numbers).

The outer for loop in the example iterates over the list of dictionaries.

The inner loop iterates over the items of the current dictionary.

The dict.items method returns a new view of the dictionary's items ((key, value) pairs).

main.py
list_of_dicts = [ {'id': 1, 'salary': 100}, {'id': 2, 'salary': 100}, {'id': 3, 'salary': 100}, ] # ๐Ÿ‘‡๏ธ dict_items([('id', 1), ('salary', 100)]) print(list_of_dicts[0].items())

On each iteration of one of the nested dictionaries, we update the key-count pair in the central Counter object.

The result is the sum of the values of all dictionary keys in the list of dictionaries.

Here is the complete code snippet.

main.py
from collections import Counter list_of_dicts = [ {'id': 1, 'salary': 100}, {'id': 2, 'salary': 100}, {'id': 3, 'salary': 100}, ] my_dict = Counter() for d in list_of_dicts: for key, value in d.items(): my_dict[key] += value # ๐Ÿ‘‡๏ธ Counter({'salary': 300, 'id': 6}) print(my_dict) total = sum(my_dict.values()) print(total) # ๐Ÿ‘‰๏ธ 306
The code for this article is available on GitHub
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev