Let's say I have a dictionary in which the keys map to integers like:
d = {'key1': 1,'key2': 14,'key3': 47}
Is there a syntactically minimalistic way to return the sum of the values in d
—i.e. 62
in this case?
USE sum() TO SUM THE VALUES IN A DICTIONARY. Call dict. values() to return the values of a dictionary dict. Use sum(values) to return the sum of the values from the previous step.
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() . You can also achieve this with a list comprehension.
Python provides an inbuilt function sum() which sums up the numbers in the list. Syntax: sum(iterable, start) iterable : iterable can be anything list , tuples or dictionaries , but most importantly it should be numbers. start : this start is added to the sum of numbers in the iterable.
As you'd expect:
sum(d.values())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With