How to sum all the values in a dictionary?


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?

10/7/2017 1:56:46 AM

Accepted Answer

As you'd expect:


In Python<3, you may want to use itervalues instead (which does not build a temporary list).

6/16/2012 9:17:19 PM

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:


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])())


This is essentially what Benjamin Peterson's six module does.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow