Calculate sum of all dictionary values in Python
This post will discuss how to calculate the sum of all the dictionary’s values in Python.
1. Using sum() function
A simple solution is to use the built-in function sum() to calculate the sum of all the dictionary’s values. The idea is to get a view of the dictionary’s values using the dict.values() function and pass it to sum().
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': d = {'A': 1, 'B': 2, 'C': 3} total = sum(d.values()) print(total) # 6 |
You can also achieve this with a list comprehension.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': d = {'A': 1, 'B': 2, 'C': 3} total = sum(d[x] for x in d) print(total) # 6 |
For floating-point dictionary’s values, consider using math.fsum() to get sum with extended precision.
2. Using reduce operation
Alternatively, you can use the functools.reduce() function to calculate the sum of the dictionary’s values with a lambda expression. Following is a simple example demonstrating usage of this:
|
1 2 3 4 5 6 7 8 9 |
from functools import reduce if __name__ == '__main__': d = {'A': 1, 'B': 2, 'C': 3} total = reduce(lambda x, y:x+y, d.values()) print(total) # 6 |
That’s all about calculating the sum of all dictionary values in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)