To sum the values of a dictionary in Python, the easiest way is with the Python sum() function used on the dictionary values.
d = {'a': 4, 'b': 5, 'c': 6}
print(sum(d.values())
#Output:
15
You can also use comprehension to sum the values of a dictionary in Python.
d = {'a': 4, 'b': 5, 'c': 6}
print(sum(d[x] for x in d)
#Output:
15
Finally, of course, you can also use a loop to sum the dictionary values of a Python dictionary.
d = {'a': 4, 'b': 5, 'c': 6}
sum = 0
for x in d:
sum = sum + d[x]
print(sum)
#Output:
15
When working with collections of data in Python, the ability to easily be able to calculate statistics is valuable.
One such situation is if you want to sum up the values in a dictionary.
You can easily sum the values of a dictionary in Python with the sum() function used on the dictionary values.
To get the values of a dictionary, you can use values() and then take the sum with sum().
Below shows you a simple example of how to easily find the sum of values in a dictionary in Python.
d = {'a': 4, 'b': 5, 'c': 6}
print(sum(d.values())
#Output:
15
How to Sum Dictionary Values Based on Key Name in Python
If you only want to sum certain values in a dictionary based on the name of the keys, then you have to do a little more work.
The easiest way to sum the values of a dictionary based on a condition is to use comprehension.
Below is a simple example showing you how to use comprehension to sum certain values of a dictionary with Python.
d = {'a': 4, 'b': 5, 'c': 6, 'd':7, 'e':8}
print(sum(value for key, value in d.items() if key in ["c","d","e"]))
#Output:
21
Hopefully this article has been useful for you to learn how to get the sum of values in a dictionary in Python.