Given a dictionary, the task is to calculate the sum of all its values. For example:
Input: {'a': 100, 'b': 200, 'c': 300}
Output: 600
Below are multiple methods to calculate the sum of dictionary values efficiently.
Using sum()
This method 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: d.values() retrieves all values from the dictionary as a view object and sum(d.values()) calculates the sum of these values directly.
Using list comprehension and sum()
This method creates a list containing the dictionary values using list comprehension and then applies sum(). It is a clean approach, but slightly slower than sum(d.values()) because it constructs a list in memory.
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 a for loop
This is a approach uses a for loop and an accumulator variable to incrementally sum the values. While being 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, current value is added to res variable using res += value.
Using map() with a lambda
map() extract values from the dictionary using a lambda function. While it avoids list creation, 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 and sum() function then calculates the sum of all these values.