[python] How to sum all the values in a dictionary?

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?

This question is related to python dictionary hash sum

The answer is


As you'd expect:

sum(d.values())

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)

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


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


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


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.


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

sum(d.values()) - "d" -> Your dictionary Variable


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

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

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to dictionary

JS map return object python JSON object must be str, bytes or bytearray, not 'dict Python update a key in dict if it doesn't exist How to update the value of a key in a dictionary in Python? How to map an array of objects in React C# Dictionary get item by index Are dictionaries ordered in Python 3.6+? Split / Explode a column of dictionaries into separate columns with pandas Writing a dictionary to a text file? enumerate() for dictionary in python

Examples related to hash

php mysqli_connect: authentication method unknown to the client [caching_sha2_password] What is Hash and Range Primary Key? How to create a laravel hashed password Hashing a file in Python PHP salt and hash SHA256 for login password Append key/value pair to hash with << in Ruby Are there any SHA-256 javascript implementations that are generally considered trustworthy? How do I generate a SALT in Java for Salted-Hash? What does hash do in python? Hashing with SHA1 Algorithm in C#

Examples related to sum

Iterating over arrays in Python 3 Get total of Pandas column Pandas: sum DataFrame rows for given columns How to find sum of several integers input by user using do/while, While statement or For statement SQL Sum Multiple rows into one Python Pandas counting and summing specific conditions SELECT query with CASE condition and SUM() Using SUMIFS with multiple AND OR conditions How to SUM parts of a column which have same text value in different column in the same row how to count the total number of lines in a text file using python