Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sum of each item in For Loop

I’m a total beginner with Python/Django and this is probably a really easy thing to do, but i can’t work out how.

I have a view that carries out some calculations within a for loop each loop creates a "value":value pair. I’m trying to add up all the values to create total.

for item in list:
    value = round(holding.price * price, 3)
    results.append({'value':value})

total = # How?

I’ve tried to loop through results, but I think because results is a list of dictionaries it doesn’t work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there an easy way?

>Solution :

You can use a list comprehension to put the value properties into a list, and then sum that list:

results = []
for item in lst:
    value = round(holding.price * price, 3)
    results.append({'value': value})

total = sum([dct['value'] for dct in results])
print(total)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading