Python - How To Sum Dictionary Values in Python

ID : 205

viewed : 112

Tags : PythonPython Dictionary

vote vote

91

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 

  • Related HOW TO?