Dictionaries
A dict stores key: value pairs, and you look up each value by its key.
Used in 127 lessons of the course, from 00.01.
A dict is a collection of key: value pairs. You write it with curly braces {}, and separate the pairs with commas.
ages = {"ana": 31, "luis": 28}
To read a value, you put the key in square brackets: ages["ana"]. Position doesn't matter, the key does. That's why a dict answers questions like "what does this term mean?" well.
Keys must be unique and unchangeable (strings, numbers, tuples). Values can be anything, even another dict or a tuple. If you repeat a key, the last one wins.
In the course you'll see lines like GLOSSARY: dict[str, tuple[str, str]] = {. Read it as: a dict whose keys are strings and whose values are tuples of two strings. The type hint describes the shape; the brace opens the contents.
Reach for it when: you need to look up a value by a name or label, like a glossary or a configuration.
Examples
Common mistake
ages = {"ana": 31}
print(ages["luis"])Why: You asked for a key that isn't in the dict.
How to write it: Check the key, or use ages.get("luis") to get None instead of an error.
Common mistake
d = {"a": 1, "a": 2}
print(d)Why: A repeated key doesn't raise: the last value replaces the earlier one.
How to write it: Use a different key for each pair.
