Neural Sync Active
Programming in Python · Week 7 — Collections continued
Registry Synced
Programming in Python · Week 7 — Collections continued
1113 words
6 min read
2026-08-16
Reading compass
Now · Week map
Week 7 — collections continued
Quiz 2 scope: Weeks 1–8 per IITM May 2026 foundation courses. Source baseline: IITM BS admissions important-dates calendar · May 2026 cycle. Times on assessments are operational conventions — verify hall ticket.
Week map
Key-value map → lookup → count frequencies → iterate keys/values
Classify → Represent → Execute → Trap-check
- Recognize: Ask: How do you count occurrences with a dict?
- Procedure: Insert key-value pairs. Overwriting key updates value. Keys must be immutable (str, int, tuple of immutables).
- Variations / traps: Watch for: KeyError when key never inserted—use get or in.
Formula chain (compressed)
dict key→value → in keys → frequency via d[k]=d.get(k,0)+1.
- Dict literal —
{k: v, ...}— map keys to values - Lookup —
d[key]— KeyError if missing - get —
d.get(key, default)— safe lookup - Frequency —
d[x] = d.get(x,0) + 1— count occurrences - Iteration —
for k in d: / d.items()— keys vs key-value pairs
Open interactive formula desk · Week 7 tab.
Deep study
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](/viewer?path=1, 2) = 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?
ChatGPT prep archive
Archived import for extra depth — complements the notes above, not official IITM material.
Core concepts
- Dict maps hashable keys to values; literal {k: v} or dict().
- Lookup: d[k] raises KeyError if missing; d.get(k, default) safe.
- Frequency: loop items, counts[x] = counts.get(x, 0) + 1.
- Iteration: d.keys(), d.values(), d.items() for pairs.
Notation & vocabulary
| Access | Behavior |
|---|---|
d[k] | value or KeyError |
d.get(k,0) | default if missing |
k in d | membership test |
Pattern families
Easy — Build small dict
Insert key-value pairs. Overwriting key updates value. Keys must be immutable (str, int, tuple of immutables).
Medium — Frequency table
Initialize empty dict. For each item in data, increment count with get pattern. Result maps value → count.
Hard — Group or invert
Group by key: dict of lists. Invert when values unique: swap keys and values carefully—collisions mean inversion is not a dict.
Drill these on the pattern atlas — filter to week 7.
Traps
- KeyError when key never inserted—use get or in.
- Lists as dict keys (unhashable).
- Iterating dict gives keys only by default in older mental models—use items for pairs.
- Assuming sorted order of keys without sorting.
Retrieval prompts
- How do you count occurrences with a dict?
- Difference between
d[k]andd.get(k)? - Why can’t a list be a dict key?
Practice loop
- Read Deep study (if present) or core concepts once.
- Recite the formula chain without looking.
- Open one easy pattern on the interactive atlas for week 7.
- Attempt without solutions; mark studied after an honest try.
- Say one trap aloud before closing the tab.