Open In App

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

Last Updated : 22 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

The task of finding the sum of all items in a dictionary in Python involves calculating the total of all values stored in a dictionary. For example, given a dictionary {‘a’: 100, ‘b’: 200, ‘c’: 300}, the sum of values would be 100 + 200 + 300 = 600.

Using sum()

This is the simplest and fastest method to find the sum of all dictionary values. It directly accesses all values using d.values() and passes them to the sum() function. This approach is highly efficient as it avoids extra list creation and leverages Python’s built-in optimization.

d = {'a': 100, 'b': 200, 'c': 300}

res = sum(d.values())
print(res)

Output
600

Explanation: res = sum(d.values()) calculates the sum of all values in the dictionary by using the values() method to retrieve the values and passing them to the sum() function.

Using list comprehension

This method creates a list containing the dictionary values using list comprehension and then applies sum(). It is a clean and readable approach, but slightly slower than sum(d.values()) because it constructs a list in memory. It can be useful when additional processing is needed while extracting values.

d = {'a': 100, 'b': 200, 'c': 300}

res = sum([d[key] for key in d])
print(res)

Output
600

Explanation : sum([d[key] for key in d]) creates a list of values from the dictionary d using list comprehension and then calculates the sum of those values using the sum() function.

Using loop

This is a traditional approach using a for loop and an accumulator variable to incrementally sum the values. It is clear and easy to understand, especially for beginners. While efficient, it is slightly slower than sum(d.values()) due to manual addition in each iteration.

d = {'a': 100, 'b': 200, 'c': 300}
res = 0

for value in d.values():
    res += value
print(res)

Output
600

Explanation: for loop iterate through the values of the dictionary d . In each iteration, the current value is added to the res variable using res += value. After the loop completes, the print(res) statement outputs the final sum of all dictionary values.

Using map()

map() extract values from the dictionary using a lambda function. It is considered functional programming style, but less readable for simple sum operations. While it avoids list creation, the lambda evaluation adds slight overhead, making it less efficient than sum(d.values()).

d = {'a': 100, 'b': 200, 'c': 300}

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

Output
600

Explanation: lambda key: d[key] retrieves the value corresponding to each key and map() applies this to all keys. sum() function then calculates the sum of all these values.  



Next Article

Similar Reads

three90RightbarBannerImg