360

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?

martineau
  • 119,623
  • 25
  • 170
  • 301
nedblorf
  • 5,135
  • 4
  • 27
  • 28
  • 2
    Just for fun: implement `sum` yourself in terms of [`reduce`](http://docs.python.org/library/functions.html) -- `reduce` is a more general form (e.g. `sum`, `min` and `max` can all be written in terms of `reduce`) and can solve other problems (e.g. `product`) easily. –  Feb 02 '11 at 23:53
  • 1
    What about Guido's saying -- I think I remember this correctly -- that reduce is going away? I'm with you. Why remove it from the language? – octopusgrabbus Jun 16 '12 at 19:04

11 Answers11

706

As you'd expect:

sum(d.values())
phihag
  • 278,196
  • 72
  • 453
  • 469
  • 1
    Well,`Python 2.7.12` also works well with `sum(d.values())` – LancelotHolmes Jan 17 '17 at 01:14
  • 7
    @LancelotHolmes Yes, but that builds a list in memory, and can thus be slower/closer to resource limits for large dictionaries. Thus, this answer says "you *may* want to use" instead of "you *must* use" when discussing Python 2. – phihag Feb 25 '17 at 08:33
  • Nice! I sought it up just because I knew there would be something like that. Not that it takes too much work to write a dead silly for loop though ;) – runlevel0 Mar 23 '18 at 14:29
  • I don't know if you love python, if you love python 3, or if really are referring to a python 2 – Lucas Vazquez Sep 23 '19 at 20:19
  • 1
    @LucasVazquez This referred to Python 2 (or 1). I removed it since it's irrelevant nowadays – even if you write new code in Python2, you can use `d.values()`. – phihag Sep 23 '19 at 20:51
71

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
20

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
octopusgrabbus
  • 10,555
  • 15
  • 68
  • 131
vz0
  • 32,345
  • 7
  • 44
  • 77
8
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

8

sum(d.values())

  • "d" -> Your dictionary Variable
Maifee Ul Asad
  • 3,992
  • 6
  • 38
  • 86
Behlul Valiyev
  • 101
  • 1
  • 2
  • 5
5

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())
Nick
  • 138,499
  • 22
  • 57
  • 95
4

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)
Tamil Selvan S
  • 562
  • 8
  • 25
3

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

Reza
  • 147
  • 1
  • 7
0

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

Rahul Patel
  • 96
  • 1
  • 4
0

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)
nemo
  • 12,241
  • 3
  • 21
  • 26
-1

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()))
zganger
  • 3,572
  • 1
  • 10
  • 13