Problem
Assume I have a dictionary with keys that map to numbers like:
d = {'key1': 1,'key2': 14,'key3': 47}
Is there a method to return the total of the values in d—in this example, 62—in a syntactically minimalistic fashion?
Asked by nedblorf
Solution #1
As you’d expect:
sum(d.values())
Answered by phihag
Solution #2
Using the itervalues() dictionary method in Python 2, which produces an iterator of the dictionary’s keys, you can avoid producing a temporary duplicate of all the values:
sum(d.itervalues())
Because the function was altered to do that in Python 3, you may just use d.values() (and itervalues() was deleted because it was no longer needed).
A utility function can be useful to make it easier to build version agnostic code that always iterates over the values of the dictionary’s keys:
import sys
def itervalues(d):
return iter(getattr(d, ('itervalues', 'values')[sys.version_info[0]>2])())
sum(itervalues(d))
Benjamin Peterson’s six module essentially does this.
Answered by martineau
Solution #3
There is, of course. Here’s how to add a dictionary’s values together.
>>> d = {'key1':1,'key2':14,'key3':47}
>>> sum(d.values())
62
Answered by vz0
Solution #4
d = {'key1': 1,'key2': 14,'key3': 47}
sum1 = sum(d[item] for item in d)
print(sum1)
You can use the for loop to accomplish this.
Answered by Kalyan Pendyala
Solution #5
The most efficient approach to get the sum, in my opinion, is to use sum(d.values()).
You can also use the reduction function with a lambda expression to calculate the sum:
reduce(lambda x,y:x+y,d.values())
Answered by Pratyush Raizada
Post is based on https://stackoverflow.com/questions/4880960/how-to-sum-all-the-values-in-a-dictionary