Dictionaries
When position is the wrong way to find something, name it instead. A dictionary looks values up by key.
A value under a name
Curly braces, and each entry is key: value. You reach in with the key rather than a number.
The key that is not there
Square brackets raise on a missing key. get returns a default instead, which is often what you want.
Looking things up
d["missing"] raises KeyError. d.get("missing") returns None, and d.get("missing", 0) returns your own fallback..items() when you want key and value together.Dictionaries: A Practical Guide
A lookup table, not a numbered row.
Quick Context
A list answers "what is at position 2?". A dictionary answers "what is stored under 'age'?". When the natural question is a name rather than a number, a dictionary is the right shape, and the lookup stays fast however many entries it holds.
Missing keys are a decision, not an accident
Reaching for a key that is absent raises KeyError, which is Python insisting you decide what should happen. get lets you say "if it is not there, use this instead" in one line, and reads better than checking first and then indexing.
Interactive Exploration Guide
- Run the first editor. Note that assigning to
person["city"]- a key that did not exist - simply adds it, and the length goes from 3 to 4. - Trigger a KeyError. Add
print(person["email"])to the second editor and run. Then change it toperson.get("email")and watch it returnNonequietly instead. - Read the loop output. The loop prints keys, and the value comes from indexing with that key.
- Swap in
.items(). Change the loop tofor key, value in person.items():and print both directly - same result, less indexing.
Key Takeaway
A dictionary maps keys to values and is the right structure whenever you would otherwise be remembering which position meant what. Square brackets raise KeyError on a missing key; get() returns a default. Iterating gives keys, and .items() gives both halves at once.