Quiz
Warm-up from lesson 6-2: which list method adds an item to the END of a list?
A dict maps keys to values
Almost every record a real program touches is key-value shaped: a user profile (name, email, plan), a settings file, the JSON that every web service sends and receives. The dictionary is Python's container for that shape, and after the list it is the type you will use most for the rest of your career.
A list answers what is at position 2? A dictionary answers what is Ada's age? It stores key: value pairs in curly braces:
ages = {"Ada": 36, "Grace": 45}| Operation | Example | Result |
|---|---|---|
| look up | ages["Ada"] | 36 |
| add or replace | ages["Alan"] = 41 | new pair stored |
| key exists? | "Grace" in ages | True |
| safe look up | ages.get("Linus", 0) | 0, no crash |
| size | len(ages) | number of pairs |
Looking up a key that is not there with brackets stops the program with a KeyError. .get(key, default) returns the default instead, which is why it powers the counting pattern you are about to write.
Code exercise · python
Run this and match each line to the table. The `.get` on the last line asks for a missing key and survives.
Quiz
`ages` is `{"Ada": 36}`. What happens when the program runs `ages["Linus"]`?
Code exercise · python
Your turn: the counting pattern, dict edition. Count how many times each letter appears in `banana` using `counts.get(ch, 0) + 1`, then print the dict.