Quiz 2

Programming in Python · Week 7 — Collections continued

1113 words
6 min read
2026-08-16T00:00:00.000Z
Python Week 1: the first filter for runtime behavior
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

dictionaries, frequency counting, grouping — concepts, pattern families, and traps for Quiz 2 week 7. # Week 7 — collections continued > **Quiz 2 scope:** Weeks 1–8 per IITM May 2026 foundation courses.

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.
Part of the Quiz 2 prep system%20%C2%B7%20%5BWeeks%201%E2%80%938%20index%5D(.%2Fmay-2026-python-quiz-2-weeks-1-8-prep) · Pattern atlas · Formula chains.

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.
  1. Dict literal{k: v, ...} — map keys to values
  2. Lookupd[key] — KeyError if missing
  3. getd.get(key, default) — safe lookup
  4. Frequencyd[x] = d.get(x,0) + 1 — count occurrences
  5. Iterationfor k in d: / d.items() — keys vs key-value pairs

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 → raises KeyError if key missing.
  • d[key] = value → insert or overwrite.
  • key in d → membership test → True if key exists.
  • len(d) → number of key-value pairs.
Mini-example:
python
scores = {"Ana": 88, "Ben": 92}
scores["Ana"]      # 88
scores["Cal"] = 75 # add new pair

Safe access

  • d.get(key) → returns None if missing (or default: d.get(key, 0)).
  • d.get(key, 0) → frequency pattern starter — return 0 when key unseen.
Mini-example:
python
counts = {}
word = "aba"
for ch in word:
    counts[ch] = counts.get(ch, 0) + 1
# counts = {'a': 2, 'b': 1}

Frequency counting pattern

python
freq = {}
for item in data:
    freq[item] = freq.get(item, 0) + 1
Alternative with defaultdict (if allowed) or if item in freq branch.

Traversal

python
for 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.
python
capitals = {}
capitals["India"] = "New Delhi"
capitals["France"] = "Paris"
Example 2 — Frequency.
python
votes = ["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.
python
freq = {"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.
python
d = {"x": 1}
d["x"] = 10   # overwrite, not duplicate key
# len(d) still 1
Example 5 — Invalid key.
python
# d[1, 2](/courses/may26-python/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 — use get or check in first.
  • 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] += 1 on missing key raises error — initialize first.
  • Confusing .keys() with values when iterating.

Diagnostic (try yourself)

  1. What does {"x": 1, "y": 2}["y"] return? What happens for ["z"]?
  2. Count letters in "hello" using get(key, 0) + 1 pattern. What is count of 'l'?
  3. Write one line to check if "admin" is a key in dict users.
  4. After d = {}; d["a"] = 1; d["a"] = 2, what is d and len(d)?
  5. Why does counts[word] = counts[word] + 1 fail on first sighting of word in 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

AccessBehavior
d[k]value or KeyError
d.get(k,0)default if missing
k in dmembership 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

  1. How do you count occurrences with a dict?
  2. Difference between d[k] and d.get(k)?
  3. Why can’t a list be a dict key?

Practice loop

  1. Read Deep study (if present) or core concepts once.
  2. Recite the formula chain without looking.
  3. Open one easy pattern on the interactive atlas for week 7.
  4. Attempt without solutions; mark studied after an honest try.
  5. Say one trap aloud before closing the tab.
Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.