Python Dict and Set Quiz: Counter, Hashing and heapq Practice
Test your Python dictionaries and sets with 12 questions and three programs on get and setdefault, Counter, defaultdict, set algebra, hashing, JSON and heapq.
- Course: Python study plan
- Module: Dictionaries and sets
- Kind: Checkpoint — cleared at 70%
- Reading time: 25 min
- Runtime: CPython 3.11
Checkpoint — Dictionaries and sets is the checkpoint that closes the Dictionaries and sets module: a graded quiz and whole-program exercises, passed at 70%.
Instructions
This checkpoint covers the whole module: dictionaries with get, setdefault, views and merging, counting and grouping with Counter and defaultdict, sets with their algebra and the ordering caveat, hashing and the equality contract that decides what can be a key, nested data and JSON with deterministic output, and the complexity table with heapq.
How it works. Twelve questions and three programs. You need 70% on the questions and every program accepted to clear the module. You can retake it as often as you like; your best score counts.
Before you start, make sure you can answer these from memory:
- When do you use
d[k],d.get(k),k in dandd.setdefault(k, v)? - What does
Counter(words).most_common(3)return, and how are ties ordered? - What does reading a missing key from a
defaultdictdo? - Why must a set never be printed directly, and what do you print instead?
- What happens to
__hash__when a class defines__eq__, and how do you fix it? - Which
json.dumpsoption makes two equal dicts serialise identically? - Which structure gives repeated minimum extraction in O(log n), and how do you get a max-heap from it?
The three programs are a word-frequency report with a deterministic tie-break, a two-snapshot comparison built on set algebra, and a task scheduler that pops the highest-priority job from a heap of tuples.
Common questions
When do you use d[k], d.get(k), k in d and d.setdefault(k, v)?
Use d[k] when the key must exist, so a KeyError exposes a bug; d.get(k, default) when absence is normal; k in d when only presence matters; and d.setdefault(k, v) to insert a default if the key is missing and use the value in one step.
What happens to __hash__ when a class defines __eq__?
Python sets __hash__ to None, so instances become unhashable and cannot be dict keys or set members. Fix it by defining __hash__ over a tuple of the same fields __eq__ compares, or use @dataclass(frozen=True).
What does reading a missing key from a defaultdict do?
It calls the factory, stores the new value under that key and returns it, so reading groups["x"] from a defaultdict(list) inserts an empty list. Test presence with in when the key must not be created as a side effect.
Exercises
Word-frequency report
Read text until the end of input. Words are whitespace tokens, case-folded, with leading and trailing punctuation stripped; empty results are ignored. Print the five most frequent words as <word> <count> with ties broken alphabetically, then distinct: <n> and hapax: <n> (words occurring once).
Input: any text. Output: up to five lines, then two summary lines.
It was the best of times, it was the worst of times.
prints
it 2
of 2
the 2
times 2
was 2
distinct: 7
hapax: 2Snapshot diff
Two snapshots of a key–value store arrive as key=value lines, separated by a line --. Using set operations on the dictionaries' keys, print the keys only in the second snapshot, the keys only in the first, and the keys in both whose values differ — each sorted and space-separated, or (none).
Input: lines, --, lines. Output: added: …, removed: …, changed: ….
a=1
b=2
c=3
--
b=2
c=4
d=5
prints
added: d
removed: a
changed: cScheduler
Jobs arrive as add priority name (lower number runs first; equal priorities run in arrival order) and run executes the next job, printing run <name> — or idle when nothing is pending. Use a heap of (priority, arrival, name) tuples. After the input ends print pending <n>.
Input: commands. Output: one line per run, then the pending count.
add 2 backup
add 1 deploy
run
add 1 alert
run
run
run
prints
run deploy
run alert
run backup
idle
pending 0In this module: Dictionaries and sets
- Dictionaries — the mapping at the centre of Python
- Counting and grouping — Counter, defaultdict and the accumulation idioms
- Sets — membership, deduplication and set algebra
- Hashing and keys — what makes an object usable in a dict or set
- Nested data and JSON
- Choosing a collection — the complexity table and heapq
- Checkpoint — Dictionaries and sets (this lesson)
← Choosing a collection — the complexity table and heapq · Defining classes — __init__, self, attributes and methods →