Quiz 2

Programming in Python · Week 8 — Collections & integration

1092 words
5 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

nested collections, mixed iteration patterns — concepts, pattern families, and traps for Quiz 2 week 8. # Week 8 — collections & integration > **Quiz 2 scope:** Weeks 1–8 per IITM May 2026 foundation courses.

Week 8 — collections & integration

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

Nested structures → layered loops → aggregate → choose right collection

Classify → Represent → Execute → Trap-check

  • Recognize: Ask: How do you reach column j of row i in a matrix list?
  • Procedure: Identify outer index (row/key) then inner (col/subkey). Trace type at each level—dict vs list.
  • Variations / traps: Watch for: Index order swapped in matrix access.

Formula chain (compressed)

list of dicts → nested loops over collections → mixed indexing.
  1. List of dicts[{...}, {...}] — records / rows
  2. Nested accessrows[i]["key"] — index then key
  3. Enumeratefor i, x in enumerate(L): — need index + value
  4. Zipzip(a, b) — parallel iteration
  5. Copy trapshallow copy shares inner refs — mutating nested structures

Deep study

Programming in Python · Week 8 — Mixed collections

Deep study for Quiz 2 week 8. Real programs combine lists, tuples, dicts, and strings — know which structure fits each sub-problem.

Week map

Choose structure → list of dicts → dict of lists → nested access → aggregate patterns → common mixed traces.

Mixed structure notation

  • List of dicts → table rows → [{"name": "A", "score": 90}, ...].
  • Dict of lists → columns keyed by field → {"names": [...], "scores": [...]}.
  • Dict of dicts → nested lookup → data[user][metric].
  • Tuple in dict → immutable key bundle → {(x, y): value} for grid cells.
Mini-example:
python
students = [
    {"id": 1, "grade": 85},
    {"id": 2, "grade": 91},
]
students[1]["grade"]   # 91

Access chain

Read inside-out: container[index_or_key][next_key]...
python
matrix = [1, 2], [3, 4](/courses/may26-python/notes/1%2C%202%5D%2C%20%5B3%2C%204)
matrix[1][0]           # 3

registry = {"team": {"lead": "Sam", "size": 5}}
registry["team"]["lead"]  # 'Sam'

Common mixed patterns

Filter and collect

python
results = []
for row in table:
    if row["score"] >= 60:
        results.append(row["name"])

Group by key

python
groups = {}
for item in items:
    k = item["category"]
    if k not in groups:
        groups[k] = []
    groups[k].append(item)

Sort list of dicts (concept)

Sort by field: sorted(rows, key=lambda r: r["score"]). Know that key picks comparison field.

Pattern families

Easy — Nested access

One or two-level lookup. Predict type after access: list element, dict value, character in string.

Medium — Build mixed structure

Construct list of dicts from parallel lists. Update nested value. Count items matching condition across records.

Hard — Aggregate over mixed data

Average scores per category. Find record with max field. Merge two list-of-dict sources by shared key.

Worked mini-examples

Example 1 — List of dicts.
python
books = [{"title": "A", "pages": 200}, {"title": "B", "pages": 150}]
total = 0
for b in books:
    total += b["pages"]
# total = 350
Example 2 — Dict of lists.
python
data = {"x": [1, 2], "y": [3, 4]}
data["x"].append(5)   # {"x": [1, 2, 5], "y": [3, 4]}
Example 3 — Filter names.
python
rows = [{"n": "a", "ok": True}, {"n": "b", "ok": False}]
passed = [r["n"] for r in rows if r["ok"]]
# ['a']
Example 4 — Tuple key.
python
grid = {}
grid[(0, 0)] = "start"
grid[(1, 0)] = "path"
grid[(0, 0)]   # 'start'
Example 5 — Type discipline.
python
record = {"tags": ["py", "stats"]}
record["tags"].append("ml")   # list inside dict — mutable
record["tags"][0]             # 'py'

Traps

  • Wrong bracket type: d["key"] vs lst[0].
  • Shallow copy of list-of-lists shares inner lists.
  • Iterating dict gives keys, not values — use .values() or .items().
  • Assuming all rows have same keys — missing key raises KeyError.
  • Modifying list while iterating — use new list or iterate copy.

Diagnostic (try yourself)

  1. Given d = {"a": [1, 2], "b": [3]}, what is d["a"][1]?
  2. Build a list of dicts with keys "name" and "age" from names = ["Kim", "Lee"] and ages = [20, 22].
  3. From records = [{"v": 3}, {"v": 7}, {"v": 5}], how would you find the dict with largest "v"?
  4. What is data[0]["x"] if data = [{"x": 10}, {"x": 20}]?
  5. Why might groups[key].append(item) require checking if key not in groups first?

ChatGPT prep archive

Archived import for extra depth — complements the notes above, not official IITM material.

Core concepts

  • Nested list: matrix as list of rows; M[i][j] row then column.
  • Dict of lists / list of dicts: common record shapes.
  • Mixed iteration: outer over keys, inner over values or indices.
  • Choose structure: fast lookup → dict; ordered sequence → list; fixed record → tuple.

Notation & vocabulary

StructureExample access
nested listgrid[r][c]
dict of listsgroups[k].append(x)
list of dictsrecords[i]["name"]

Pattern families

Easy — Access nested element

Identify outer index (row/key) then inner (col/subkey). Trace type at each level—dict vs list.

Medium — Double loop aggregate

Sum all cells: outer rows, inner columns. Or count per category using dict of counts inside loop over records.

Hard — Integrate prior patterns

Combine search, min/max, and frequency on nested data. State invariant: what each loop variable represents. Prefer clear names over i,j when semantic.
Drill these on the pattern atlas — filter to week 8.

Traps

  • Index order swapped in matrix access.
  • Mutating shared inner list across dict keys unintentionally.
  • Deep copy vs shallow when resetting rows.
  • Wrong loop variable used in inner body.

Retrieval prompts

  1. How do you reach column j of row i in a matrix list?
  2. When use dict of lists vs list of dicts?
  3. What goes wrong if inner lists are aliased?

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 8.
  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.