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?
In Python 2 you can avoid making a temporary copy of all the values by using the itervalues()
dictionary method, which returns an iterator of the dictionary's keys:
sum(d.itervalues())
In Python 3 you can just use d.values()
because that method was changed to do that (and itervalues()
was removed since it was no longer needed).
To make it easier to write version independent code which always iterates over the values of the dictionary's keys, a utility function can be helpful:
import sys
def itervalues(d):
return iter(getattr(d, ('itervalues', 'values')[sys.version_info[0]>2])())
sum(itervalues(d))
This is essentially what Benjamin Peterson's six
module does.
simplest/silliest solution:
https://trinket.io/python/a8a1f25353
d = {'key1': 1,'key2': 14,'key3': 47}
s = 0
for k in d:
s += d[k]
print(s)
or if you want it fancier:
https://trinket.io/python/5fcd379536
import functools
d = {'key1': 1,'key2': 14,'key3': 47}
s = functools.reduce(lambda acc,k: acc+d[k], d, 0)
print(s)
sum
yourself in terms ofreduce
--reduce
is a more general form (e.g.sum
,min
andmax
can all be written in terms ofreduce
) and can solve other problems (e.g.product
) easily. – user166390