Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - sum values in dictionary

I have got pretty simple list:

example_list = [     {'points': 400, 'gold': 2480},     {'points': 100, 'gold': 610},     {'points': 100, 'gold': 620},     {'points': 100, 'gold': 620} ] 

How can I sum all gold values? I'm looking for nice oneliner.

Now I'm using this code (but it's not the best solution):

total_gold = 0 for item in example_list:     total_gold += example_list["gold"] 
like image 269
Mateusz Jagiełło Avatar asked Jul 27 '12 17:07

Mateusz Jagiełło


People also ask

How do you sum a value in a dictionary Python?

It is pretty easy to get the sum of values of a python dictionary. You can first get the values in a list using the dict. values(). Then you can call the sum method to get the sum of these values.

Can you use some function for calculating the sum of the values of 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.

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.

How do you determine the number of values in a dictionary?

Use len() to count dictionary items The len() method returns the total length of a dictionary, or more precisely, the total number of items in the dictionary.


1 Answers

sum(item['gold'] for item in myList) 
like image 60
g.d.d.c Avatar answered Oct 10 '22 22:10

g.d.d.c