Python Program to find Sum of Items in a Dictionary

Write a Python Program to find the Sum of Items in a Dictionary with a practical example.

Python Program to find Sum of Items in a Dictionary Example

In this program, we are using the sum function and dict.values function to find the sum of dictionary values. The sum function returns the sum of all the values in a Dictionary. Refer to the Python Dictionary.

myDict = {'x': 250, 'y':500, 'z':410}
print("Dictionary: ", myDict)

# Print Values using get
print("\nSum of Values: ", sum(myDict.values()))
Python Program to find Sum of all Items in a Dictionary

Calculate Sum of Items in a Dictionary using values()

This Python program uses a for loop along with the values function to add values to a dictionary.

myDict = {'x': 250, 'y':500, 'z':410}
print("Dictionary: ", myDict)
total = 0

# Print Values using get
for i in myDict.values():
    total = total + i
    
print("\nThe Total Sum of Values : ", total)

The sum of Dictionary items output.

Dictionary: {'x': 250, 'y':500, 'z':410}

The Total Sum of Values : 1240

Sum of Items in a Dictionary using for loop

In this Python program, we are using a Python for loop example to iterate over each element in this Dictionary. We are adding those dictionary values to the total variable inside the loop.

myDict = {'x': 250, 'y':500, 'z':410}
print("Dictionary: ", myDict)
total = 0

# Print Values using get
for i in myDict:
    total = total + myDict[i]
    
print("\nThe Total Sum of Values : ", total)
Dictionary: {'x': 250, 'y':500, 'z':410}

The Total Sum of Values : 1160

Sum of dictionary items using list comprehension

The program below uses a list comprehension to access the dictionary items and applies the sum() function to them. Refer to a Python list comprehension.

d = {'x': 250, 'y':500, 'z':410}

result = sum([d[key] for key in d])
print(result)
1160

Sum of dictionary items using map and lambda

Here, the lambda anonymous function accepts a value and returns the dictionary value corresponding to a given key. Next, map() applies this expression to every dictionary value. Finally, sum() adds those dictionary items. Refer to the Python map and Python lambda functions.

d = {'x': 150, 'y':550, 'z':300}

result = sum(map(lambda key: d[key], d))
print(result)
1000

Also Read