← Python Foundations
10 / 27
Lesson 10 — Dictionary methods
Read dicts safely
Reading d["key"] crashes with a KeyError when the key is missing. get() returns None instead, or a default you choose: d.get("x", 0). To walk through a dict, items() gives you each key together with its value, so one loop sees both.
prices = {"tea": 3, "cake": 5}
for item, price in prices.items():
print(item, price)
Why it matters: real data often has missing fields, and looping over pairs is how you print reports or totals from a dict.
Want it another way?
Task
Loop over the dict and print "key = value" for each pair.
Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.
Test your knowledge
A quick 3-question quiz on this lesson — instant feedback.