Home > Net >  How to get the sum of values in a list within a dictionary?
How to get the sum of values in a list within a dictionary?

Time:04-08

This a simplified question for an assignment I am struggling with. The goal is to get the sum of the numbers in the 'Paid' list within the dictionary. I am receiving a type error: TypeError: string indices must be integers

This is my current code:

dict1 = {"JS" : {"Paid" : [200, 400, 500, 600]}}
total = sum(d['Paid'] for d in dict1)
print(total)

CodePudding user response:

for d in dict1: just iterates over keys in dictionary dict1. To get sum of the list you can use next example:

dict1 = {"JS": {"Paid": [200, 400, 500, 600]}}
total = sum(v for d in dict1.values() for v in d["Paid"])
print(total)

Prints:

1700

CodePudding user response:

dict1 = {"JS" : {"Paid" : [200, 400, 500, 600]}}

total = sum(dict1["JS"]["Paid"])

# output: 1700
print(total)

CodePudding user response:

I guess the most simple way to do this is simply accessing the list and then sum it:

dict1 = {"JS" : {"Paid" : [200, 400, 500, 600]}}    
total = sum(dict1["JS"]["Paid"])
print(total)

What you tried to do didn't make that much sense, because the pattern i for i in range, as I like to call it, works fine to list, but not for dicts. When you iterate over a list, the interpreter would understand you are iterating over indices that are integers, so I'll have i[0], i[1], etc. With a dict, i["JS"] wouldn't make sense as a iterative method, and so the interpreter complains that your "string indices" should be integers. Good luck with your assignment :)

  • Related