Python Dictionaries: Looking Things Up by Name, Not Number
Map keys to values with Python dictionaries, avoid KeyError crashes with .get(), and loop cleanly over keys and items.
You'll learn when to use a dictionary (dict) instead of a list, how to read missing keys safely with .get(), and how to loop over .items(). Assumes basic Python lists and loops.
1. Lists count by number; dicts look up by name
If you store Gerald's stats in a list ["Gerald", 12, 0.4], you have to memorize that index 1 means days_left and index 2 means will_to_live. Six months later, nobody remembers.
A dictionary (dict) pairs keys (names) with values, wrapped in curly braces {}:
gerald = {
"name": "Gerald",
"days_left": 12,
"coffees": 3,
}
print(gerald["name"])
gerald["coffees"] += 1
gerald["status"] = "surviving"
print(gerald)Gerald
{'name': 'Gerald', 'days_left': 12, 'coffees': 4, 'status': 'surviving'}2. Reading safely with .get()
Bracket lookup (gerald["salary"]) crashes with KeyError if the key doesn't exist. When a key might be missing, use .get(key, default):
print(gerald.get("salary", "classified"))classifiedUse .get() to count words: counts[word] = counts.get(word, 0) + 1. Try it on ["tea", "coffee", "tea"].
3. Looping over dictionaries
Use .items() to get both the key and value on each pass:
for key, value in gerald.items():
print(f"{key}: {value}")name: Gerald
days_left: 12
coffees: 4
status: survivingCommon mistakes
| Error | What it means | Fix |
|---|---|---|
KeyError: 'email' | Key 'email' is not in the dict | Use .get('email', default) or check if 'email' in d: |
TypeError: unhashable type: 'list' | Tried to use a mutable list as a dict key | Use an immutable key (str, int, tuple) |
Practice
- What does
{"a": 1}.get("b", 0)return?
Answer: 0.
What you learned
- Dictionaries map unique keys to values (
{key: value}). .get(key, default)avoidsKeyErrorwhen a key might be absent.for k, v in d.items():loops over both keys and values cleanly.