Module 3: Collections and Data Transformations
Sets and Dictionaries: Uniqueness and Lookup
Sets and Dictionaries: Uniqueness and Lookup
Sets model unique membership and set algebra. Dictionaries map hashable keys to values and naturally represent configurations, records, counts, indexes, and JSON-like objects.
Module: Module 3: Collections and Data Transformations
Core mental model
This lesson is built around four connected ideas. Read them as a decision framework, then prove each one with the walkthrough.
- Set union, intersection, and difference compare groups directly.
- Dictionary get handles a missing key with an explicit default.
- items iterates key-value pairs without a second lookup.
- Set elements and dictionary keys must be hashable.
Walkthrough
expected = {"lint", "test", "package"}
completed = {"lint", "test"}
print("missing:", expected - completed)
counts = {}
for level in ["INFO", "ERROR", "INFO"]:
counts[level] = counts.get(level, 0) + 1
for level, count in counts.items():
print(level, count)Set difference says exactly which stages are missing. The count dictionary accumulates a frequency table and items exposes both parts for reporting.
Hands-on lab
Compare expected and observed test names, report missing and unexpected tests, and count PASS, FAIL, and SKIP. Include duplicates and an empty result set.
What to watch for
- Converting to a set discards duplicates and may lose meaningful order.
- mapping[key] raises KeyError when absence is valid.
- Dictionary membership tests keys, not values.
Engineering checklist
- Connect the lesson's mental model to the choices made in the walkthrough.
- Test the normal case, an empty or boundary case, and one invalid case.
- Keep external input, side effects, and reusable logic in clearly separated layers.
- Prefer the clearest correct implementation before optimizing or generalizing it.
Completion check
You can implement the lab without copying the example, explain the core concepts in your own words, and show tests or terminal output that demonstrate the expected and failure paths.