Coder Perfect

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


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:


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:


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


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

Answered by vz0

Solution #4

d = {'key1': 1,'key2': 14,'key3': 47}
sum1 = sum(d[item] for item in d)

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