Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 875
nedblorf Avatar asked Feb 02 '11 23:02

nedblorf


People also ask

How do you find the sum of all values in a dictionary?

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.

Can you use sum for calculating the sum of the values of a dictionary?

Using sum() function A simple solution is to use the built-in function sum() to calculate the sum of all the dictionary's values. The idea is to get a view of the dictionary's values using the dict. values() function and pass it to sum() . You can also achieve this with a list comprehension.

How do you sum all values in a list Python?

Python provides an inbuilt function sum() which sums up the numbers in the list. Syntax: sum(iterable, start) iterable : iterable can be anything list , tuples or dictionaries , but most importantly it should be numbers. start : this start is added to the sum of numbers in the iterable.


1 Answers

As you'd expect:

sum(d.values()) 
like image 143
phihag Avatar answered Sep 22 '22 15:09

phihag