Saturday, May 16, 2009

How to sum the values of a Python dictionary

Suppose that we have a Python dictionary,
x = {'a': 3, 'b': 2, 'c':7}

and, we want to add the values i.e. 3 + 2 + 7 = 12.

Here are the three ways to add the values.


Using list comprehension

>>> x = {'a': 3, 'b': 2, 'c':7}
>>> sum([i for i in x.values()])
12

Using for loop I

>>> x = {'a': 34, 'b': 2, 'c':7}
>>> total = 0
>>> for i in x.values():
total += i

Using for loop II

>>> x = {'a': 34, 'b': 2, 'c':7}
>>> total = 0
>>> for key in x.keys():
total += x[key]