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"]
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.
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.
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.
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.
sum(item['gold'] for item in myList)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With