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

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/deep/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?