Records and collections
In chapter 1, a record became one dict, and a dataset became a list of records. This chapter shows the tools that hold and reshape those records.
Here is the shop from the SQL chapters as Python data. Each order is one dict. The three lists are the data for every example in this chapter:
| order_id | customer_id | status | amount | order_date |
|---|---|---|---|---|
| 101 | 1 | paid | 40.0 | 2026-01-03 |
| 102 | 1 | paid | 25.0 | 2026-01-10 |
| 103 | 2 | refunded | 60.0 | 2026-01-11 |
| 104 | 3 | paid | 15.5 | 2026-01-15 |
| 105 | 3 | pending | None | 2026-01-20 |
| 106 | 4 | paid | 80.0 | 2026-01-21 |
| customer_id | name | country |
|---|---|---|
| 1 | Asha | IN |
| 2 | Ben | GB |
| 3 | Carla | US |
| 4 | Dev | None |
| 5 | Omar | IN |
| order_id | product | quantity |
|---|---|---|
| 101 | Pen | 2 |
| 101 | Notebook | 1 |
| 102 | Bag | 1 |
| 103 | Lamp | 1 |
| 104 | Pen | 3 |
| 106 | Chair | 1 |
| 106 | Lamp | 1 |
orders = [
{"order_id": 101, "customer_id": 1, "status": "paid",
"amount": 40.0, "order_date": "2026-01-03"},
{"order_id": 102, "customer_id": 1, "status": "paid",
"amount": 25.0, "order_date": "2026-01-10"},
{"order_id": 103, "customer_id": 2, "status": "refunded",
"amount": 60.0, "order_date": "2026-01-11"},
{"order_id": 104, "customer_id": 3, "status": "paid",
"amount": 15.5, "order_date": "2026-01-15"},
{"order_id": 105, "customer_id": 3, "status": "pending",
"amount": None, "order_date": "2026-01-20"},
{"order_id": 106, "customer_id": 4, "status": "paid",
"amount": 80.0, "order_date": "2026-01-21"},
]
customers = [
{"customer_id": 1, "name": "Asha", "country": "IN"},
{"customer_id": 2, "name": "Ben", "country": "GB"},
{"customer_id": 3, "name": "Carla", "country": "US"},
{"customer_id": 4, "name": "Dev", "country": None},
{"customer_id": 5, "name": "Omar", "country": "IN"},
]
order_items = [
{"order_id": 101, "product": "Pen", "quantity": 2},
{"order_id": 101, "product": "Notebook", "quantity": 1},
{"order_id": 102, "product": "Bag", "quantity": 1},
{"order_id": 103, "product": "Lamp", "quantity": 1},
{"order_id": 104, "product": "Pen", "quantity": 3},
{"order_id": 106, "product": "Chair", "quantity": 1},
{"order_id": 106, "product": "Lamp", "quantity": 1},
]
print(len(orders))
print(orders[0])| output |
|---|
| 6 |
| {'order_id': 101, 'customer_id': 1, 'status': 'paid', 'amount': 40.0, 'order_date': '2026-01-03'} |
What you will learn
A collection is one value that holds many values. Python has four main collections:
- list: items in order. You can change it.
- tuple: items in order. You cannot change it.
- dict: pairs of a key and a value.
- set: different values, with no repeats.
Four tools in this chapter match SQL ideas you know:
| In SQL | In Python |
|---|---|
| JOIN | a dict lookup |
| GROUP BY | a dict of lists (defaultdict) |
| COUNT for each group | Counter |
| DISTINCT | a set |
You also learn why a dict lookup is fast, and how to use two fields together as one key.
