Iterating a Dictionary

When you loop over a dictionary, you get its keys. To get each key and its value together, use the items method.

scores = {"Maya": 84, "Leo": 72, "Noah": 91}

for name, score in scores.items():
    if score >= 80:
        print(name)

Output:

Maya
Noah

items() gives each pair as a tuple of two values. The for line unpacks it into name and score. The pairs come in the order they were added, and the if prints only the names with a score of 80 or higher.

If you loop over the dictionary itself, you get only the keys. When you need the keys in sorted order, wrap the dictionary in sorted:

scores = {"Maya": 84, "Leo": 72, "Noah": 91}

for name in sorted(scores):
    print(name)

Output:

Leo
Maya
Noah

Do not add or remove keys while you loop over the same dictionary. Instead, collect the changes during the loop, and make them after the loop ends.

In the exercise, print the stock report and the total.