简体   繁体   中英

Summing values in Python list of dictionaries

I have this code where I am trying to append to a dictionary and after the loop terminates, print out the name and saved_this_month in dictionary format, plus print out the sum of the saved_this_month . The latter part I am having issues with, in this case, the total_savings variable. I think I am trying to pull the values for index in position 1 (the amounts) and sum them, but clearly, I am wrong.

Any ideas? Thanks.

savings_list = []

while True:
    bank = input('Enter the name of the bank:')
    savings_amount = float(input('Enter the amount saved:'))

    savings_list.append({
        "name": bank,
        "saved_this_month": savings_amount
        })
    total_savings = sum(savings_list[1]) **this is the prob line I think**

    cont = input('Want to add another? (Y/N)')
    if cont == 'N':
        break;

print(savings_list)
print(total_savings)

If all you want to do is sum the savings amount entered, why not use a variable external to the while loop?

savings_list = []
total_savings = 0  # Define out here

while True:
    bank = input('Enter the name of the bank:')
    savings_amount = float(input('Enter the amount saved:'))

    savings_list.append({
        "name": bank,
        "saved_this_month": savings_amount
        })
    total_savings += savings_amount  # just a simple sum

    cont = input('Want to add another? (Y/N)')
    if cont == 'N':
        break;

print(savings_list)
print(total_savings)

If, however, you want to be fancy and calculate the sum after you have loaded the savings_list , you will need to convert the list of dicts into a list of something that sum knows how to handle. Try a list comprehension ( EDIT : or, even better, a generator statement ):

total_savings = sum(x["saved_this_month"] for x in savings_list)

Unrolling the list comprehension:

a = []
for x in savings_list:
    a.append(x["saved_this_month"])
total_savings = sum(a)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM