Sum Dictionary Values in Python

  1. Sum Values in Python Dictionary With the for Loop
  2. Sum Values in Python Dictionary With the sum() Function

In this tutorial, we will introduce how to sum values in a Python dictionary.

Sum Values in Python Dictionary With the for Loop

The first method involves the use of the for loop. We iterate over every value in the dictionary and store the final result in a variable, which is declared outside the loop.

Let’s see the following example.

d1 = {'a' : 15,'b' : 18,'c' : 20}

total = 0

for i in d1.values():
    total += i

print(total)

Output:

53

The values() function returns a list of dictionary values.

Sum Values in Python Dictionary With the sum() Function

The sum function is used to return the sum of an interable in Python. We can eliminate the use of the for loop by using the sum function. For example,

d1 = {'a' : 15,'b' : 18,'c' : 20}
print(sum(d1.values()))

Output:

53
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python Dictionary

  • Sort a Python Dictionary by Value
  • Sort Dictionary by Key in Python