Lecture Notes — Lecture 13: Dictionaries and Sets

Companion to the lecture plan and the worked examples. Read the Definitions before class, the Explanation after it; the practice questions and the lecture quiz close the loop.

Definitions

Explanation

Lists answer 'in what order?'; dictionaries answer 'about what?'. A dictionary maps keys to values, so 'how many times did the appear?' is one lookup instead of a scan. Building a tally is the canonical first use: walk the items, add one to each key's slot, starting from zero for newcomers. Sets are the sibling structure for presence questions: who is in both courses, who is in exactly one. The set operations (union, intersection, difference) are the questions themselves - naming the operation IS the solution. The advanced step is choosing the structure on purpose: lists preserve order and allow duplicates; dictionaries preserve insertion order and give fast lookup by key; sets give fast membership and deduplicate. The same tally written over a list of words becomes quadratic if you count with list scans - the structure choice is the complexity choice. By the end you should ask, for every accumulation task: am I counting (dictionary), membership-testing (set), or sequencing (list)?

Examples

The lecture's worked examples live in examples.md; the case studies this lecture builds on are worked in class from the projector. The case sequence with difficulties:

Common misconceptions

Summary and key takeaways

  1. Dictionaries count, sets test membership, lists order - choose the structure that matches the question.
  2. The tally pattern (get-or-zero, add one) solves most first-pass data problems.
  3. Set operations ARE the questions: union = either, intersection = both, difference = only.
  4. Structure choice is complexity choice: list scans are O(n); dict/set lookups are O(1) average.
  5. State what happens for a missing key before writing the lookup.

Practice questions

Where this leads

Next lecture: Functions with Purpose. The quiz below checks this lecture's essentials before we build on them.