How to sum all the values in a dictionary?
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Ocean Floor
--
Chapters
00:00 How To Sum All The Values In A Dictionary?
00:21 Accepted Answer Score 736
00:29 Answer 2 Score 21
00:40 Answer 3 Score 73
01:23 Answer 4 Score 10
01:31 Thank you
--
Full question
https://stackoverflow.com/questions/4880...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #dictionary #hash #sum
#avk47
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Ocean Floor
--
Chapters
00:00 How To Sum All The Values In A Dictionary?
00:21 Accepted Answer Score 736
00:29 Answer 2 Score 21
00:40 Answer 3 Score 73
01:23 Answer 4 Score 10
01:31 Thank you
--
Full question
https://stackoverflow.com/questions/4880...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #dictionary #hash #sum
#avk47
ACCEPTED ANSWER
Score 736
As you'd expect:
sum(d.values())
ANSWER 2
Score 73
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.
ANSWER 3
Score 21
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
ANSWER 4
Score 10
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