13.1 Dictionaries
Store and query records by key.
Before you start
Work through the earlier fundamentals chapters. Use a Python 3 interpreter and run each example locally.
Core concepts
A dictionary maps unique, hashable keys to values. Assignment replaces an existing value for the same key. Dictionaries preserve insertion order; lookups are typically constant time on average.
Use direct indexing when a key is required and get() when a missing key is expected. A missing key accessed with brackets raises KeyError. Values can be mutable, so copying a dictionary does not recursively copy nested objects.
Worked example
server = {"name": "web-01", "state": "running"}
server["owner"] = "platform"
print(server.get("region", "unknown"))
for key, value in server.items():
print(key, value)
Mini lab
Build a dictionary that counts occurrences in ["running", "stopped", "running"]. Expected result: {"running": 2, "stopped": 1}.
Hint
Start with the smallest input. Print intermediate values while exploring, then replace those prints with checks of the expected result.Show a solution
counts = {}
for state in ["running", "stopped", "running"]:
counts[state] = counts.get(state, 0) + 1
print(counts)
Knowledge check
What happens when you assign to an existing dictionary key?
Check your answer
Its value is replaced; a second identical key is not added.Common mistake
Never use a mutable list as a dictionary key. Use a tuple of hashable values if you need a composite key.
Completion checklist
- Run the example and explain its output.
- Complete the mini lab without copying the solution.
- Test an edge case and explain how the code handles it.
- Answer the knowledge check in your own words.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form