Summing integers in a list of dictionaries

Question:

How do I use the Loop Summing Pattern to calculate and print the total score of all the games in this list of dictionaries? The Sum function is not allowed, nor is importing functions:

games = [
    {"Name": "UD", "Score": 27, "Away?": False},
    {"Name": "Clemson", "Score": 14, "Away?": True},
    {"Name": "Pitt", "Score": 32, "Away?": True},
]

I would suppose that there is some way of accessing it via a for loop?

for i in games: ......

for i in games["Score"]:

gets SyntaxError: unexpected EOF while parsing

I tried:

sum_hold = sum(d.get("Score", 0) for d in games)

but I am not allowed to use the sum function for the assignment

Asked By: baylee

||

Answers:

You have a list of dictionaries that you can iterate. Once you get a single game, the Score is easy to grab.

games = [
    {"Name": "UD", "Score": 27, "Away?": False},
    {"Name": "Clemson", "Score": 14, "Away?": True},
    {"Name": "Pitt", "Score": 32, "Away?": True},
]

total = 0
for game in games:
    total += game.get("Score", 0)

print(total)
Answered By: tdelaney

You may want to write it this way (same method Tim Roberts mentioned in the comment):

games = [
{"Name": "UD", "Score": 27, "Away?": False},
{"Name": "Clemson", "Score": 14, "Away?": True},
{"Name": "Pitt", "Score": 32, "Away?": True},]

sum_hold = 0

for i in games:
  sum_hold += i['Score']

print(sum_hold)
Answered By: Meh
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.