How to sum all the values in a dictionary?

PythonDictionaryHashSum

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

As you'd expect:

sum(d.values())

Solution 2 - Python

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.

Solution 3 - Python

Sure there is. Here is a way to sum the values of a dictionary.

>>> d = {'key1':1,'key2':14,'key3':47}
>>> sum(d.values())
62

Solution 4 - Python

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

you can do it using the for loop

Solution 5 - Python

I feel sum(d.values()) is the most efficient way to get the sum.

You can also try the reduce function to calculate the sum along with a lambda expression:

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

Solution 6 - Python

sum(d.values())

  • "d" -> Your dictionary Variable

Solution 7 - Python

USE sum() TO SUM THE VALUES IN A DICTIONARY.

Call dict.values() to return the values of a dictionary dict. Use sum(values) to return the sum of the values from the previous step.

d = {'key1':1,'key2':14,'key3':47}
values = d.values()
#Return values of a dictionary    
total = sum(values)
print(total)

Solution 8 - Python

phihag's answer (and similar ones) won't work in python3.

For python 3:

d = {'key1': 1,'key2': 14,'key3': 47}
sum(list(d.values()))

Update! There are complains that it doesn't work! I just attach a screenshot from my terminal. Could be some mismatch in versions etc.

enter image description here

Solution 9 - Python

You could consider 'for loop' for this:

  d = {'data': 100, 'data2': 200, 'data3': 500}
  total = 0
  for i in d.values():
        total += i

total = 800

Solution 10 - Python

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)

Solution 11 - Python

You can get a generator of all the values in the dictionary, then cast it to a list and use the sum() function to get the sum of all the values.

Example:

c={"a":123,"b":4,"d":4,"c":-1001,"x":2002,"y":1001}

sum(list(c.values()))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnedblorfView Question on Stackoverflow
Solution 1 - PythonphihagView Answer on Stackoverflow
Solution 2 - PythonmartineauView Answer on Stackoverflow
Solution 3 - Pythonvz0View Answer on Stackoverflow
Solution 4 - PythonKalyan PendyalaView Answer on Stackoverflow
Solution 5 - PythonPratyush RaizadaView Answer on Stackoverflow
Solution 6 - PythonBehlul ValiyevView Answer on Stackoverflow
Solution 7 - PythonTamil Selvan SView Answer on Stackoverflow
Solution 8 - PythonRezaView Answer on Stackoverflow
Solution 9 - PythonRahul PatelView Answer on Stackoverflow
Solution 10 - PythonnemoView Answer on Stackoverflow
Solution 11 - Pythonuser12988654View Answer on Stackoverflow