# What is the best way to add all the values in a dictionary?

## 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?

## Solution #1

As you’d expect:

``````sum(d.values())
``````

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

sum(itervalues(d))
``````

Benjamin Peterson’s six module essentially does this.

## 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
``````

## 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.

``````reduce(lambda x,y:x+y,d.values())