Read Code Fast

Lesson 6 Collections

6 min read · Python · Quiz

group-by, index-by-id, dedupe, zip and partition

What you'll learn

  • Name the five collection shapes: group-by, index-by-id, dedupe, zip and partition
  • Ask the trap question for each shape
  • Spot the quiet data loss: overwritten keys, dropped items and exhausted generators

AI code loves to reshape lists: group them, index them, dedupe them, pair them, split them. Each shape has a one-word name, and a one-word trap.

The idea

Five shapes cover most of it. group-by: one key, a list of items for each key. index-by-id: one key, one item, for fast lookup. dedupe: keep each value once. zip: walk two lists side by side. partition: split one list into two, the items that match and the ones that don't.

Name the shape from what comes out, not from how the loop looks. Then ask the trap question for that shape: what if two items share a key? What counts as the "same" value? What if the two lists have different lengths? What if an item fits neither half?

reshape.py
1by_customer = defaultdict(list)2for order in orders:3    by_customer[order["customer_id"]].append(order)45by_id = {o["id"]: o for o in orders}67cities = list(dict.fromkeys(c["city"] for c in customers))89paid = [o for o in orders if o["paid"]]10unpaid = [o for o in orders if not o["paid"]]1112pairs = list(zip(names, prices))
  1. Line 1 Group-by. defaultdict(list) creates an empty list the first time a customer appears. With a plain {}, the .append would fail.
  2. Line 5 Index-by-id. One order per id. If two orders share an id, the later one silently wins.
  3. Line 7 Dedupe. dict.fromkeys keeps each value once and keeps the order. list(set(...)) also dedupes, but the order is lost.
  4. Line 12 Zip. If prices is shorter than names, zip stops at the shorter list and drops the rest without a word.

Take away

  • Five shapes: group-by, index-by-id, dedupe, zip, partition.
  • Name the shape from what comes out, then ask its trap question.
  • Traps: duplicate keys overwrite, "same" has a meaning, lists differ in length, halves must not overlap or leave gaps.

Quiz: test yourself

7 questions: a quick quiz, then a review drill. Pick an answer to see why it's right.