Python lesson 21

Looping Through a Dictionary

Visit every label and every value, one pair at a time.

Three Ways to Walk Through

Looping over a dictionary gives you the keys. .values() gives you the values instead. .items() gives you both at once, which is usually the one you want.

for key in scores: # just the names
for value in scores.values(): # just the numbers
for key, value in scores.items(): # both

scores = {"Nova": 40, "Blaze": 65, "Echo": 22}
for name, points in scores.items():
    print(name, "scored", points)

Put the Scoreboard Together

Keys or Values?

ages = {"Sam": 9, "Ada": 11}
for thing in ages:
    print(thing)

Add Up Every Score

Run it. The loop adds each value to a running total.

scores = {"Nova": 40, "Blaze": 65, "Echo": 22}
total = 0
for points in scores.values():
    total = total + points
print("Total points:", total)

Find the Winner

Loop through the scores and keep track of who is in the lead.

scores = {"Nova": 40, "Blaze": 65, "Echo": 22}
best_name = ""
best_score = 0
for name, points in scores.items():
    if points > best_score:
        best_score = points
        best_name = name
print("Winner:", best_name, "with", best_score)

Give Everyone a Bonus

Add 10 points to every player, then print the new scoreboard.

scores = {"Nova": 40, "Blaze": 65, "Echo": 22}
for name in scores:
    scores[name] = scores[name] + 10
for name, points in scores.items():
    print(name, "now has", points)

What you can do on CodeIt

Run the example, change one part, and use the result to check your understanding before moving to the next lesson.