Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python program to find the sum of all items in a dictionary

  • Difficulty Level : Easy
  • Last Updated : 13 Apr, 2022

Given a dictionary in Python, write a Python program to find the sum of all items in the dictionary.

Examples: 

Input : {‘a’: 100, ‘b’:200, ‘c’:300}
Output : 600

Input : {‘x’: 25, ‘y’:18, ‘z’:45}
Output : 88

 

Approach #1 : Using Inbuilt sum() Function
Use the sum function to find the sum of dictionary values.

Python3




# Python3 Program to find sum of
# all items in a Dictionary
 
# Function to print sum
 
 
def returnSum(myDict):
 
    list = []
    for i in myDict:
        list.append(myDict[i])
    final = sum(list)
 
    return final
 
 
# Driver Function
dict = {'a': 100, 'b': 200, 'c': 300}
print("Sum :", returnSum(dict))
Output
Sum : 600

Approach #2 : Using For loop to iterate through values using values() function
Iterate through each value of the dictionary using values() function and keep adding it to the sum. 

Python3




# Python3 Program to find sum of
# all items in a Dictionary
 
# Function to print sum
 
 
def returnSum(dict):
 
    sum = 0
    for i in dict.values():
        sum = sum + i
 
    return sum
 
 
# Driver Function
dict = {'a': 100, 'b': 200, 'c': 300}
print("Sum :", returnSum(dict))
Output
Sum : 600

Approach #3: Using For loop to iterate through items of Dictionary
Iterate through each item of the dictionary and simply keep adding the values to the sum variable. 

Python3




# Python3 Program to find sum of
# all items in a Dictionary
 
# Function to print sum
 
 
def returnSum(dict):
 
    sum = 0
    for i in dict:
        sum = sum + dict[i]
 
    return sum
 
 
# Driver Function
dict = {'a': 100, 'b': 200, 'c': 300}
print("Sum :", returnSum(dict))
Output
Sum : 600

Approach #4 : Using dictionary.sum() method to find the sum of values taken out through dictionary.values() function.

Python3




# Python3 Program to find sum of
# all items in a Dictionary
 
# Function to print sum
 
 
def returnSum(dict):
    return sum(dict.values())
 
 
# Driver Function
dict = {'a': 100, 'b': 200, 'c': 300}
print("Sum :", returnSum(dict))
Output
Sum : 600

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!