Skip to main content

Phase 4 🗃️ — Data Structures

Topics: Lists, tuples, dictionaries, sets, nested structures

Data structures are how you organise and store collections of data. Mastering them is the key to writing elegant, efficient Python.


🔄 Exercise Flow


📚 Prerequisites

Before starting these exercises, make sure you've read:

  • Lists — Creating, modifying, and iterating lists
  • Tuples — Immutable sequences
  • Dictionaries — Key-value pairs
  • Sets — Unordered collections of unique elements

🔰 Starter: Gradebook Manager

Time: 12 minutes

Build a simple gradebook that stores student names and scores, then calculates averages and finds the highest score.

Learning Objectives

  • Create and manipulate lists
  • Use dictionary key-value pairs
  • Iterate over data structures with for loops
  • Use built-in functions like sum(), len(), max()

Starter Code

# Starter: Gradebook Manager

# Dictionary mapping student names to their list of scores
gradebook = {
"Alice": [85, 92, 78],
"Bob": [70, 88, 95],
"Charlie": [90, 85, 82],
"Diana": [65, 72, 80]
}

# TODO: For each student, calculate their average score
# TODO: Find which student has the highest average
# TODO: Print a report showing each student's scores, average, and letter grade
# A: >= 90, B: >= 80, C: >= 70, D: >= 60, F: < 60
# TODO: Calculate the class average

# Your code here 👇

Expected Output

=== GRADES REPORT ===
Alice: [85, 92, 78] → Avg: 85.0 → B
Bob: [70, 88, 95] → Avg: 84.3 → B
Charlie: [90, 85, 82] → Avg: 85.7 → B
Diana: [65, 72, 80] → Avg: 72.3 → C
─────────────────────────
Class Average: 81.8
Top Student: Charlie (85.7)
─────────────────────────

⭐ Medium: Library Management System

Time: 22 minutes

Build a library management system that tracks books, members, and borrowing using nested dictionaries, sets, and tuples.

Learning Objectives

  • Work with nested dictionaries (dict of dicts)
  • Use sets for unique membership tracking
  • Use tuples as fixed records
  • Perform lookups, additions, and removals across structures

Starter Code

# Medium: Library Management System

# Books: ISBN -> {title, author, copies, available}
library = {
"978-0": {"title": "Python Crash Course", "author": "Eric Matthes", "copies": 3, "available": 3},
"978-1": {"title": "Clean Code", "author": "Robert Martin", "copies": 2, "available": 2},
"978-2": {"title": "Automate the Boring Stuff", "author": "Al Sweigart", "copies": 4, "available": 4},
}

# Members: set of member IDs
members = {"M001", "M002", "M003"}

# Borrowing records: list of tuples (member_id, isbn, borrow_date)
borrow_records = []

# TODO 1: Implement a function to borrow a book
# - Check if member exists and book is available
# - Decrease available count, add record
# TODO 2: Implement a function to return a book
# - Increase available count, update record
# TODO 3: Implement a function to find books by author
# TODO 4: Implement a function to show all overdue books (assume 14-day limit)
# TODO 5: Show a summary of the library status

# Your code here 👇

Expected Output

=== LIBRARY STATUS ===
Members: 3 registered
Total Books: 9 copies (9 available)

Borrowing: Alice borrowed "Python Crash Course" on 2025-01-15
Bob borrowed "Clean Code" on 2025-01-10

Overdue: Bob — "Clean Code" (5 days overdue)

Search by "Al Sweigart":
→ "Automate the Boring Stuff" (4 copies available)

🏆 Hard: E-Commerce Product Catalog & Cart

Time: 35 minutes

Build a complete e-commerce backend that manages a product catalog (nested dicts), a shopping cart (list of tuples), and an order history (set of completed orders) with search, filtering, and sorting.

Learning Objectives

  • Design complex nested data structures
  • Transform data between lists, dicts, and sets
  • Implement search and filter operations
  • Sort data by different keys (price, rating, name)
  • Build a complete data-management application

Starter Code

# Hard: E-Commerce Product Catalog & Cart

# Nested catalog: category -> product_id -> {details}
catalog = {
"Electronics": {
"E001": {"name": "Wireless Mouse", "price": 29.99, "rating": 4.5, "stock": 50},
"E002": {"name": "Mechanical Keyboard", "price": 89.99, "rating": 4.8, "stock": 30},
"E003": {"name": "USB-C Hub", "price": 34.99, "rating": 4.2, "stock": 100},
},
"Books": {
"B001": {"name": "Python Crash Course", "price": 39.99, "rating": 4.7, "stock": 25},
"B002": {"name": "Fluent Python", "price": 49.99, "rating": 4.9, "stock": 15},
},
"Clothing": {
"C001": {"name": "Python Logo T-Shirt", "price": 24.99, "rating": 4.3, "stock": 200},
}
}

# Shopping cart: list of (product_id, qty) tuples
cart = []

# Completed orders: set of order IDs
completed_orders = set()

# TODO 1: Display catalog by category with product count per category
# TODO 2: Implement search by name (case-insensitive, partial match)
# TODO 3: Implement filter by price range and minimum rating
# TODO 4: Implement sort by price (asc/desc) or rating
# TODO 5: Add/remove items from cart (with stock validation)
# TODO 6: Calculate cart total with tax (8%) and shipping ($5 if total < $50)
# TODO 7: Checkout — move cart to completed_orders, update stock, clear cart
# TODO 8: Show order history with total spent per order

# Your code here 👇

Expected Output

=== PRODUCT CATALOG ===
Electronics (3 products)
E001 — Wireless Mouse ($29.99) ⭐4.5 [50 in stock]
E002 — Mechanical Keyboard ($89.99) ⭐4.8 [30 in stock]
E003 — USB-C Hub ($34.99) ⭐4.2 [100 in stock]

Books (2 products)
B001 — Python Crash Course ($39.99) ⭐4.7 [25 in stock]
B002 — Fluent Python ($49.99) ⭐4.9 [15 in stock]

Clothing (1 product)
C001 — Python Logo T-Shirt ($24.99) ⭐4.3 [200 in stock]

Search: "python"
→ Python Crash Course (Book)
→ Fluent Python (Book)
→ Python Logo T-Shirt (Clothing)

🛒 Cart (3 items): $154.97
Subtotal: $154.97
Tax (8%): $12.40
Shipping: $0.00 (Free!)
Total: $167.37

💡 Tips for Success

  • Use dictionary methods.get(), .keys(), .values(), .items() are your friends. They make code cleaner and safer.
  • Lists for order, sets for uniqueness, dicts for lookups — pick the right tool.
  • defaultdict and Counter from collections are worth knowing once you're comfortable with basics.
  • Deep vs shallow copy — when nesting structures, use copy.deepcopy() if you need independent copies.

← Back to Exercises