Lists & Dictionaries
Python’s most powerful built-in data structures
📖 Concept Recap
- Lists are ordered, mutable sequences:
[1, 2, 3]. Access by index..append(),.remove(),.sort(). - Dicts are key-value stores:
{"name": "Alice", "age": 22}. Access by key..get(key, default)is safer than[key]. - List comprehension:
[x*2 for x in numbers if x > 0]— one-line filtering and transformation. - Dict iteration:
for key in dgives keys.for k, v in d.items()gives both. - Sorting with key:
sorted(students, key=lambda s: s['gpa'], reverse=True)
👀 Worked Example
A shopping cart combining lists and dicts:
Exercise 1 — Student Roster Manager
Complete the roster manager by filling in the blanks.
.append() to add to a list. reverse=True sorts highest-first. len(grades) for the count in the average calculation.Exercise 2 — Word Frequency Analyzer
Given the word list below, write code to find:
- The unique words (no duplicates)
- Word frequency (how many times each word appears)
- The most common word
- Words with more than 4 letters
set(words) for unique words. Build frequency with a loop or {} and .get(). max(freq, key=lambda w: freq[w]) finds the most common. Use a list comprehension with len(w) > 4.Exercise 3 — Group by Grade
Write a function group_by_grade(grade_dict) that takes a dictionary of name: score pairs and returns a new dictionary grouping names by letter grade (A/B/C/D/F). Test with at least 8 students.
Expected output structure: {"A": ["Alice", "Carol"], "B": ["Bob"], ...}
result.setdefault("A", []).append(name) to avoid KeyErrors.Mini Project — Shopping Cart System
Build a complete shopping cart. Start with an inventory of 5 products (name, price, stock). Write these 4 functions:
add_to_cart(cart, product, quantity)— checks stock, adds to cart dictremove_from_cart(cart, product)— removes entirely from cartcalculate_total(cart, inventory)— returns total priceprint_receipt(cart, inventory)— prints a formatted receipt
Then simulate: add 3 items (one twice), remove 1, print the receipt.
{"apple": 3}. In add_to_cart, check if quantity <= inventory[product]["stock"]. The receipt should show each item, quantity, unit price, line total, and a grand total.✅ Lab 5 Complete!
You’ve mastered list comprehensions, dict operations, sorting with key functions, and built a complete data-driven shopping system. These skills are the foundation of data analysis.
Continue to Lab 6: String Methods →