Dictionaries and Sets
Model key-value data with dictionaries, enforce uniqueness with sets, iterate safely, and select lookup structures based on the questions your program asks.
Before this lesson
Model records and indexes with dictionaries
Use sets for membership and uniqueness
Handle missing keys deliberately
The short answer
A dictionary maps unique hashable keys to values; a set stores unique hashable members. Both provide fast average-case membership checks. Choose keys that represent stable identity and handle absence explicitly.
Build the mental model
Dictionary iteration yields keys by default; items yields key-value pairs. Direct indexing expresses that a key must exist and raises KeyError otherwise. get expresses that absence is expected and can provide a default.
The central idea in this lesson is lookup collections. Read the rule, predict a concrete outcome, and then run the smallest example that can confirm or reject the prediction. This separates knowledge from familiarity with syntax.
Make the design choice explicit
Use a set when only membership matters, such as visited identifiers or unique tags. Set union, intersection, and difference express comparisons without nested loops. Dictionary insertion order is preserved, but semantic ordering should still be explicit.
inventory = {"paper": 12, "pens": 5, "clips": 40}
requested = {"paper", "clips", "folders"}
available = requested & inventory.keys()
missing = requested - inventory.keys()
print(f"Available: {sorted(available)}")
print(f"Missing: {sorted(missing)}")Expected output
Available: ['clips', 'paper'] Missing: ['folders']
Trace the example before running it. Identify each input, transformation, returned value, and side effect. Then change one boundary value and explain why the new behavior follows from the rule rather than memorizing the output.
Recognize failure modes
Keys must be hashable and should not change while stored. Avoid setdefault or defaultdict until their mutation behavior matches the requirement. Never use a mutable object as a shared default value returned for missing keys.
Use a professional practice loop
Turn the concept into a repeatable workflow: write down the expected behavior, implement one coherent change, run a representative example, and retain a regression check. If the result surprises you, capture the exact input and error before changing anything.
Review the program for names, boundaries, and hidden side effects. A solution is complete when another developer can understand its contract, reproduce its setup, and verify both the successful path and one meaningful failure path.
Quick knowledge check
Answer before you reveal.
01When should direct dictionary indexing be preferred over get?
When the key is required by the program’s invariant and absence should be treated as an error.
02What four steps make the practice loop reliable?
Predict the behavior, make one coherent change, run it, and retain a check that detects regression.
Exercise
Practice challenge
Build a word-frequency dictionary from a sentence and a set of unique words, then report words in descending frequency with alphabetical ties.
Requirements
- The successful path produces the documented result
- At least one boundary or invalid case is handled deliberately
- Calculation or domain logic is separated from console interaction
Optional extension: Add one automated regression check for the most important rule.
Open in Python compilerLesson checkpoint
One small step locks it in
Mark this lesson complete, then keep the momentum going.
Clear up the details
Frequently asked questions
Is lookup collections only important in large programs?
No. Small programs reveal the same rules with less noise, and learning the rule early prevents fragile habits from becoming architecture.
Should I memorize every API used here?
No. Memorize the mental model and how to verify behavior. Use documentation for exact names and parameters when needed.
How do I know the exercise is finished?
Meet every success criterion, test at least one boundary or failure case, and explain why the output follows from the code.