# SUM OF DICTIONARY VALUES PYTHON

d = "key1": 1,"key2": 14,"key3": 47Is tright here a syntactically minimalistic method to rerevolve the sum of the worths in d—i.e. 62 in this case?   In Python 2 you have the right to protect against making a momentary copy of all the values by using the itervalues() dictionary technique, which retransforms an iterator of the dictionary"s keys:

sum(d.itervalues())In Python 3 you deserve to simply usage d.values() because that strategy was changed to carry out that (and itervalues() was rerelocated considering that it was no longer needed).

You watching: Sum of dictionary values python

To make it much easier to write variation independent code which always iteprices over the worths of the dictionary"s keys, a utility function have the right to be helpful:

import sysdef itervalues(d): rerevolve iter(getattr(d, ("itervalues", "values")>2>)())sum(itervalues(d))This is fundamentally what Benjamin Peterson"s 6 module does. Sure tright here is. Here is a way to amount the worths of a dictionary. d = "key1": 1,"key2": 14,"key3": 47sum1 = sum(d for item in d)print(sum1)you deserve to do it making use of the for loop

I feel sum(d.values()) is the most effective method to acquire the sum.

You can additionally attempt the minimize function to calculate the amount along with a lambda expression:

reduce(lambda x,y:x+y,d.values())
phihag"s answer (and also similar ones) won"t occupational in python3.

For python 3:

d = "key1": 1,"key2": 14,"key3": 47sum(list(d.values()))Update! Tright here are complains that it does not work! I simply connect a screenswarm from my terminal. Could be some misenhance in versions etc. You can consider "for loop" for this:

d = "data": 100, "data2": 200, "data3": 500 complete = 0 for i in d.values(): total += itotal = 800

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

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

d = "key1":1,"key2":14,"key3":47values = d.values()#Rerotate worths of a dictionary complete = sum(values)print(total)
simplest/silliest solution:

https://trinket.io/python/a8a1f25353

d = "key1": 1,"key2": 14,"key3": 47s = 0for k in d: s += dprint(s)or if you desire it fancier:

https://trinket.io/python/5fcd379536

import functoolsd = "key1": 1,"key2": 14,"key3": 47s = functools.reduce(lambda acc,k: acc+d, d, 0)print(s)
You can gain a generator of all the worths in the dictionary, then actors it to a list and usage the sum() function to acquire the sum of all the worths.

Example:

c="a":123,"b":4,"d":4,"c":-1001,"x":2002,"y":1001sum(list(c.values()))
Thanks for contributing a response to Stack Overflow!

But avoid

Asking for assist, clarification, or responding to other answers.Making statements based on opinion; back them up via recommendations or personal experience.

To learn even more, see our tips on composing excellent answers.