Python program to find the sum of all items in a dictionary
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()FunctionUse sum function to find the sum of dictionary values.# Python3 Program to find sum of# all items in a Dictionary# Function to print sumdefreturnSum(myDict):sum=0foriinmyDict:sum=sum+myDict[i]returnsum# Driver Functiondict={'a':100,'b':200,'c':300}print("Sum :", returnSum(dict))Output:
Sum : 600
- Approach #2 : Using For loop to iterate through values using
values()functionIterate through each value of the dictionary usingvalues()function and keep adding it to the sum.# Python3 Program to find sum of# all items in a Dictionary# Function to print sumdefreturnSum(dict):sum=0foriindict.values():sum=sum+ireturnsum# Driver Functiondict={'a':100,'b':200,'c':300}print("Sum :", returnSum(dict))Output:
Sum : 600
- Approach #3 : Using For loop to iterate through items of DictionaryIterate through each item of the dictionary and simply keep adding the values to the sum variable.
# Python3 Program to find sum of# all items in a Dictionary# Function to print sumdefreturnSum(dict):sum=0foriinmyDict:sum=sum+dict[i]returnsum# Driver Functiondict={'a':100,'b':200,'c':300}print("Sum :", returnSum(dict))Output:
Sum : 600