593 words
3 min read
Visual companion
Python
Type and operator map
Python Week 1: the first filter for runtime behavior
View
Revision summary
What this note is really saying
Short form
# Programming in Python · Week 7 — Dictionaries and frequency Deep study for Quiz 2 week 7. Dictionaries map keys to values — ideal for counting, lookup tables, and grouping.

Programming in Python · Week 7 — Dictionaries and frequency
Deep study for Quiz 2 week 7. Dictionaries map keys to values — ideal for counting, lookup tables, and grouping.
Week map
Dict creation → key access → add/update → traversal → frequency counting →
get and defaults.Dictionary notation
d = {"a": 1, "b": 2}→ mapping from keys to values → keys must be hashable (immutable types).d[key]→ lookup value → raisesKeyErrorif key missing.d[key] = value→ insert or overwrite.key in d→ membership test →Trueif key exists.len(d)→ number of key-value pairs.
Mini-example:
pythonscores = {"Ana": 88, "Ben": 92} scores["Ana"] # 88 scores["Cal"] = 75 # add new pair
Safe access
d.get(key)→ returnsNoneif missing (or default:d.get(key, 0)).d.get(key, 0)→ frequency pattern starter — return 0 when key unseen.
Mini-example:
pythoncounts = {} word = "aba" for ch in word: counts[ch] = counts.get(ch, 0) + 1 # counts = {'a': 2, 'b': 1}
Frequency counting pattern
pythonfreq = {} for item in data: freq[item] = freq.get(item, 0) + 1
Alternative with
defaultdict (if allowed) or if item in freq branch.Traversal
pythonfor key in d: print(key, d[key]) for key, val in d.items(): print(key, val)
.keys(), .values(), .items() return views of dict contents.Pattern families
Easy — Lookup and update
Read value by key. Add new key. Check membership with
in. Predict KeyError vs get.Medium — Frequency count
Count occurrences in list or string. Find most common. Report keys with count above threshold.
Hard — Nested dict and grouping
Dict of dicts:
d[user][month] = score. Group records by category. Merge counts from two sources.Worked mini-examples
Example 1 — Basic build.
pythoncapitals = {} capitals["India"] = "New Delhi" capitals["France"] = "Paris"
Example 2 — Frequency.
pythonvotes = ["yes", "no", "yes", "yes", "no"] tally = {} for v in votes: tally[v] = tally.get(v, 0) + 1 # {'yes': 3, 'no': 2}
Example 3 — Max frequency key.
pythonfreq = {"a": 3, "b": 7, "c": 2} best_key = None best_val = -1 for k, v in freq.items(): if v > best_val: best_val = v best_key = k # best_key = 'b'
Example 4 — Overwrite.
pythond = {"x": 1} d["x"] = 10 # overwrite, not duplicate key # len(d) still 1
Example 5 — Invalid key.
python# d[1, 2](/courses/deep/notes/1%2C%202) = 5 # TypeError — list not hashable d[(1, 2)] = 5 # OK — tuple is hashable
Traps
- Using
d[key]when key may be absent — usegetor checkinfirst. - Lists as keys — not allowed.
- Assuming dict preserves insertion order in very old Python mental models (3.7+ preserves order, but logic should not depend on order unless stated).
freq[key] += 1on missing key raises error — initialize first.- Confusing
.keys()with values when iterating.
Diagnostic (try yourself)
-
What does
{"x": 1, "y": 2}["y"]return? What happens for["z"]? -
Count letters in
"hello"usingget(key, 0) + 1pattern. What is count of'l'? -
Write one line to check if
"admin"is a key in dictusers. -
After
d = {}; d["a"] = 1; d["a"] = 2, what isdandlen(d)? -
Why does
counts[word] = counts[word] + 1fail on first sighting ofwordin an empty dict?