How to get the sum of the values in a Python dictionary?
Published on Aug. 22, 2023, 12:17 p.m.
To get the sum of the values in a Python dictionary, you can use the built-in sum()
function. Here’s an example:
my_dict = {'key1': 10, 'key2': 45, 'key3': 23}
sum_values = sum(my_dict.values())
print(sum_values) # Output: 78
In this example, sum()
is called with my_dict.values()
as an argument, which returns a view object of the dictionary’s values. The resulting sum of values is stored in the sum_values
variable and printed to the console.
Note that this method assumes that the values in the dictionary are numeric types that can be added together. If not, you may get a TypeError
when trying to add non-numeric types together.