![]() |
VOOZH | about |
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.
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.
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.
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.
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.
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.
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.
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()).
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.