Nested collections
Real data is rarely flat. A list of students, each with several grades; a shop with categories, each with products. You model this by putting collections inside other collections.
A list of dictionaries
The most common shape: many records, each with named fields. It looks just like JSON from a web API.
Python
students = [
{"name": "Asha", "grade": 92, "city": "Mumbai"},
{"name": "Leo", "grade": 78, "city": "London"},
{"name": "Mei", "grade": 85, "city": "Osaka"},
]
for s in students:
print(f"{s['name']} from {s['city']}: {s['grade']}")
top = max(students, key=lambda s: s["grade"])
print("Top student:", top["name"])A dictionary of lists
Python
courses = {
"Python": ["Asha", "Leo"],
"SQL": ["Mei"],
}
courses["SQL"].append("Raj")
courses.setdefault("Java", []).append("Asha")
print(courses)
for course, people in courses.items():
print(course, "has", len(people), "learner(s)")A grid: a list of lists
A two-dimensional grid is a list of rows, each row a list:
Python
board = [
["X", "O", "X"],
[" ", "X", "O"],
["O", " ", "X"],
]
print(board[1][2]) # row 1, column 2
board[1][0] = "O"
for row in board:
print(" | ".join(row))Reaching deep inside
Chain the lookups one level at a time, from the outside in:
Python
shop = {
"name": "CodeMIRAI Store",
"categories": [
{"title": "Books", "items": [{"name": "Python 101", "price": 25}]},
{"title": "Mugs", "items": [{"name": "Hello World mug", "price": 12}]},
],
}
print(shop["categories"][0]["items"][0]["name"])
for cat in shop["categories"]:
for item in cat["items"]:
print(f"{cat['title']}: {item['name']} costs {item['price']}")Python
wrong = [[0] * 3] * 3
wrong[0][0] = 1
print(wrong)
right = [[0] * 3 for _ in range(3)]
right[0][0] = 1
print(right)Finished this lesson?Mark it complete to earn +20 XP and move your progress on.