Programming in Python · Week 8 — Collections & integration
1092 words
5 min read
2026-08-16T00:00:00.000Z
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.
- List of dicts —
[{...}, {...}]— records / rows - Nested access —
rows[i]["key"]— index then key - Enumerate —
for i, x in enumerate(L):— need index + value - Zip —
zip(a, b)— parallel iteration - Copy trap —
shallow copy shares inner refs— mutating nested structures
Open interactive formula desk · Week 8 tab.
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:
pythonstudents = [ {"id": 1, "grade": 85}, {"id": 2, "grade": 91}, ] students[1]["grade"] # 91
Access chain
Read inside-out:
container[index_or_key][next_key]...pythonmatrix = [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
pythonresults = [] for row in table: if row["score"] >= 60: results.append(row["name"])
Group by key
pythongroups = {} 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.
pythonbooks = [{"title": "A", "pages": 200}, {"title": "B", "pages": 150}] total = 0 for b in books: total += b["pages"] # total = 350
Example 2 — Dict of lists.
pythondata = {"x": [1, 2], "y": [3, 4]} data["x"].append(5) # {"x": [1, 2, 5], "y": [3, 4]}
Example 3 — Filter names.
pythonrows = [{"n": "a", "ok": True}, {"n": "b", "ok": False}] passed = [r["n"] for r in rows if r["ok"]] # ['a']
Example 4 — Tuple key.
pythongrid = {} grid[(0, 0)] = "start" grid[(1, 0)] = "path" grid[(0, 0)] # 'start'
Example 5 — Type discipline.
pythonrecord = {"tags": ["py", "stats"]} record["tags"].append("ml") # list inside dict — mutable record["tags"][0] # 'py'
Traps
- Wrong bracket type:
d["key"]vslst[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)
-
Given
d = {"a": [1, 2], "b": [3]}, what isd["a"][1]? -
Build a list of dicts with keys
"name"and"age"fromnames = ["Kim", "Lee"]andages = [20, 22]. -
From
records = [{"v": 3}, {"v": 7}, {"v": 5}], how would you find the dict with largest"v"? -
What is
data[0]["x"]ifdata = [{"x": 10}, {"x": 20}]? -
Why might
groups[key].append(item)require checkingif key not in groupsfirst?
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
| Structure | Example access |
|---|---|
| nested list | grid[r][c] |
| dict of lists | groups[k].append(x) |
| list of dicts | records[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
- How do you reach column j of row i in a matrix list?
- When use dict of lists vs list of dicts?
- What goes wrong if inner lists are aliased?
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 8.
- Attempt without solutions; mark studied after an honest try.
- Say one trap aloud before closing the tab.