04. Data structures — Exercises
These exercises practice every idea of the data structures lesson. They use the course datasets: readings from data/readings.txt, rows of data/sensors.csv, products from data/products.csv and the customer records of data/customers.json.
How to work:
- Read the task and the expected output.
- Copy the setup code and the starter code into a script (for example
exercise.py). Replace each to-do comment with your code. - Run the script with
python exercise.pyfrom your project folder, which holds thedata/folder. Compare your output with the expected output. - Stuck? Open one hint at a time. Open the solution only after a real attempt.
Each solution ends with assert checks. Add the same checks to your own code.
Many exercises use the 20 customer records of data/customers.json. Put these lines at the top of your script. The with open(...) line opens the file; module 07 explains it.
import copyimport json
with open("data/customers.json", encoding="utf-8") as f: customers = json.load(f)["customers"]Warm-up
Section titled “Warm-up”M04-W01 · Summarize a list of readings
Section titled “M04-W01 · Summarize a list of readings”Lines 13 to 22 of data/readings.txt hold ten temperatures of sensor S1 in °C. Store them in a list. Print the count, the minimum, the maximum, the range (max − min) and the mean, as shown.
count=10 min=21.0 max=22.4range=1.4 mean=21.70readings = [22.4, 22.2, 21.3, 22.3, 22.0, 21.9, 21.2, 21.3, 21.4, 21.0]# TODO: print count, min, max, range and mean (2 decimals)Hint 1
len(), min(), max() and sum() all accept a list.
Hint 2
The mean is sum(readings) / len(readings). Format the range and the mean with :.1f and :.2f, because a difference of floats can carry a tiny error.
Solution
import math
readings = [22.4, 22.2, 21.3, 22.3, 22.0, 21.9, 21.2, 21.3, 21.4, 21.0]count = len(readings)lowest = min(readings)highest = max(readings)mean = sum(readings) / countprint(f"count={count} min={lowest} max={highest}")print(f"range={highest - lowest:.1f} mean={mean:.2f}")assert count == 10assert lowest <= mean <= highestassert math.isclose(mean, 21.7)count=10 min=21.0 max=22.4range=1.4 mean=21.70How it works:
- The list keeps the ten readings in time order.
min()andmax()scan the whole list.len()gives the count.sum() / len()is the mean. The asserts check that it lies between the extremes.
Alternative: the statistics module has statistics.mean(readings) and statistics.median(readings) (module 09).
M04-W02 · Predict the output: list methods
Section titled “M04-W02 · Predict the output: list methods”Predict the output: write down what each print() shows. Pay attention to which methods return a value and which return None.
Acceptance criteria:
- Write your prediction line by line, then run the code.
- Your prediction matches the Output in the solution, and you can explain each line.
readings = [21.0, 21.9, 21.4]readings.append([22.1, 22.0])print(readings)print(len(readings))readings.pop()readings.extend([22.1, 22.0])print(readings)result = readings.sort()print(result, readings)readings.insert(0, readings.pop())print(readings)# TODO: write your prediction for each print() before you run itHint 1
append() adds its argument as one element, even when the argument is a list. extend() adds each element.
Hint 2
sort() changes the list and returns None. pop() returns the element it removes.
Solution
readings = [21.0, 21.9, 21.4]readings.append([22.1, 22.0])print(readings)print(len(readings))readings.pop()readings.extend([22.1, 22.0])print(readings)result = readings.sort()print(result, readings)readings.insert(0, readings.pop())print(readings)assert result is Noneassert readings == [22.1, 21.0, 21.4, 21.9, 22.0][21.0, 21.9, 21.4, [22.1, 22.0]]4[21.0, 21.9, 21.4, 22.1, 22.0]None [21.0, 21.4, 21.9, 22.0, 22.1][22.1, 21.0, 21.4, 21.9, 22.0]How it works:
append([22.1, 22.0])adds one element, a list. The outer list now has 4 elements.pop()removes that inner list.extend()then adds 22.1 and 22.0 as two elements.sort()sorts in place and returnsNone, soresultisNone.readings.pop()removes and returns the largest value, 22.1.insert(0, ...)puts it at the front.
Alternative: readings += [22.1, 22.0] does the same as extend().
M04-W03 · Read the fields of a customer record
Section titled “M04-W03 · Read the fields of a customer record”The fourth record of data/customers.json is customer C00004. Print the name, the plan, the city, the number of tags and the phone number. Then print the email domain (the text after @). Use the customers list from the setup.
C00004 Lucas Martin premiumcity: Philadelphiatags: 3 ['loyalty', 'student', 'vip']phone: +1-555-652-5039email domain: example.comrecord = customers[3]# TODO: print name, plan, city, tag count, phone and email domainHint 1
The city sits in a nested dict: record["address"]["city"].
Hint 2
Many records have no phone key, so use record.get("phone"). email.split("@") gives a list of two parts.
Solution
record = customers[3]print(record["customer_id"], record["name"], record["plan"])print("city:", record["address"]["city"])print("tags:", len(record["tags"]), record["tags"])print("phone:", record.get("phone", "none"))_, domain = record["email"].split("@")print("email domain:", domain)assert record["customer_id"] == "C00004"assert domain == "example.com"C00004 Lucas Martin premiumcity: Philadelphiatags: 3 ['loyalty', 'student', 'vip']phone: +1-555-652-5039email domain: example.comHow it works:
customers[3]is the fourth record, because indexes start at 0.- A chain of
[]lookups reads the nestedaddressdict. record.get("phone", "none")returns the phone when the key exists, and"none"otherwise.split("@")returns a list of two strings. Unpacking keeps the second one and ignores the first with_.
Alternative: record["email"].partition("@")[2] also gives the domain, and works even when there is no @.
M04-W04 · Count the distinct products
Section titled “M04-W04 · Count the distinct products”These are the product ids of every sales line of store S07 (New York) from 2024-03-04 to 2024-03-10, from data/sales.csv. Print the number of lines, the number of distinct products, the first five distinct ids in sorted order, and whether P003 and P018 were sold.
lines: 21distinct products: 15first five: ['P001', 'P005', 'P007', 'P011', 'P012']P003 sold: False | P018 sold: Truelines = ["P018", "P027", "P011", "P026", "P005", "P014", "P018", "P016", "P019", "P030", "P022", "P011", "P007", "P017", "P026", "P016", "P023", "P012", "P001", "P023", "P012"]# TODO: make a set, then print the four resultsHint 1
set(lines) removes the duplicates.
Hint 2
A set has no order. sorted(my_set) returns a sorted list, which you can slice.
Solution
lines = ["P018", "P027", "P011", "P026", "P005", "P014", "P018", "P016", "P019", "P030", "P022", "P011", "P007", "P017", "P026", "P016", "P023", "P012", "P001", "P023", "P012"]products = set(lines)print("lines:", len(lines))print("distinct products:", len(products))print("first five:", sorted(products)[:5])print("P003 sold:", "P003" in products, "| P018 sold:", "P018" in products)assert len(products) == 15assert "P003" not in productslines: 21distinct products: 15first five: ['P001', 'P005', 'P007', 'P011', 'P012']P003 sold: False | P018 sold: TrueHow it works:
set(lines)keeps one copy of each id. 21 lines hold 15 distinct products.sorted()turns the set into a sorted list, so the report is stable from run to run.inon a set is a fast membership test.
Alternative: len(dict.fromkeys(lines)) also counts distinct ids, and list(dict.fromkeys(lines)) keeps them in the order of their first sale.
M04-W05 · Fix the bug: a tuple with one element
Section titled “M04-W05 · Fix the bug: a tuple with one element”Fix the bug: a monitoring script should loop over a tuple of sensor ids. With only sensor S1 configured, it prints each character instead.
sensor_ids = ("S1") # TODO: fix this linefor sensor_id in sensor_ids: print("checking", sensor_id)print(type(sensor_ids))The fixed script prints:
checking S1<class 'tuple'>Hint 1
Print type(sensor_ids) before the fix. Is it a tuple?
Hint 2
The comma makes a tuple, not the parentheses.
Solution
sensor_ids = ("S1",)for sensor_id in sensor_ids: print("checking", sensor_id)print(type(sensor_ids))assert len(sensor_ids) == 1assert sensor_ids[0] == "S1"checking S1<class 'tuple'>How it works:
("S1")is the string"S1"in parentheses. A loop over a string gives its characters,Sand1.("S1",)is a tuple with one element. The loop runs once.
Alternative: use a list, ["S1"], if the configuration may grow or change at run time. A list with one element needs no trailing comma.
M04-W06 · Unpack a sensor row with a star
Section titled “M04-W06 · Unpack a sensor row with a star”This row of data/sensors.csv has six fields: timestamp, sensor id, temperature, humidity, vibration and status. Unpack it in one line so that the timestamp, sensor id and status get their own names and the three measurements land in a list. Print the result as shown.
S4 fail [24.88, 56.0, 12.92]2024-05-01T08:00:00: vibration 12.92 mm/srow = ("2024-05-01T08:00:00", "S4", 24.88, 56.0, 12.92, "fail")# TODO: unpack with *measurements, then printHint 1
A starred name can sit in the middle: first, *middle, last = items.
Hint 2
You need four names: timestamp, sensor_id, *measurements, status.
Solution
row = ("2024-05-01T08:00:00", "S4", 24.88, 56.0, 12.92, "fail")timestamp, sensor_id, *measurements, status = rowtemperature, humidity, vibration = measurementsprint(sensor_id, status, measurements)print(f"{timestamp}: vibration {vibration} mm/s")assert measurements == [24.88, 56.0, 12.92]assert status == "fail"S4 fail [24.88, 56.0, 12.92]2024-05-01T08:00:00: vibration 12.92 mm/sHow it works:
- The plain names take the fields at the start and the end. The starred name takes the rest.
- A starred name always gets a list, even when it unpacks a tuple.
- A second unpacking gives each measurement its own name.
Alternative: without the star, write six names: timestamp, sensor_id, temperature, humidity, vibration, status = row. The star version keeps working if the file later gains more measurement columns.
M04-W07 · Predict the output: alias or copy?
Section titled “M04-W07 · Predict the output: alias or copy?”Predict the output: a script keeps the price list of three Sports products and tries to make a sale version.
Acceptance criteria:
- Write your prediction line by line, then run the code.
- Your prediction matches the Output in the solution, and you can say for each name whether it refers to the original list.
prices = [129.99, 34.99, 279.0]sale = pricessale[0] = 99.99backup = prices.copy()backup[1] = 29.99print(prices)print(sale)print(backup)print(sale is prices, backup is prices, backup == prices)# TODO: write your prediction before you run itHint 1
sale = prices does not copy anything. prices.copy() does.
Hint 2
is asks “same object?”. == asks “equal values?”.
Solution
prices = [129.99, 34.99, 279.0]sale = pricessale[0] = 99.99backup = prices.copy()backup[1] = 29.99print(prices)print(sale)print(backup)print(sale is prices, backup is prices, backup == prices)assert sale is pricesassert backup is not prices[99.99, 34.99, 279.0][99.99, 34.99, 279.0][99.99, 29.99, 279.0]True False FalseHow it works:
saleandpricesare two names for one list. Changingsale[0]changespricestoo.backupis a new list, made after the first change, so it starts with 99.99.- Changing
backup[1]does not touchprices. The two lists are now different, so==isFalse.
Alternative: sale = [round(p * 0.8, 2) for p in prices] builds a sale list without touching the original at all.
M04-W08 · Convert units with a list comprehension
Section titled “M04-W08 · Convert units with a list comprehension”Convert the readings of exercise W01 to Fahrenheit with a list comprehension, rounded to 1 decimal. Then use a second comprehension to keep only the Celsius readings of at least 22.0 °C.
[72.3, 72.0, 70.3, 72.1, 71.6, 71.4, 70.2, 70.3, 70.5, 69.8][22.4, 22.2, 22.3, 22.0]readings = [22.4, 22.2, 21.3, 22.3, 22.0, 21.9, 21.2, 21.3, 21.4, 21.0]# TODO: fahrenheit = [...]# TODO: warm = [...]Hint 1
The pattern is [expression for c in readings]. The expression is round(c * 9 / 5 + 32, 1).
Hint 2
A filter goes at the end: [c for c in readings if c >= 22.0].
Solution
readings = [22.4, 22.2, 21.3, 22.3, 22.0, 21.9, 21.2, 21.3, 21.4, 21.0]fahrenheit = [round(c * 9 / 5 + 32, 1) for c in readings]warm = [c for c in readings if c >= 22.0]print(fahrenheit)print(warm)assert len(fahrenheit) == len(readings)assert all(c >= 22.0 for c in warm)[72.3, 72.0, 70.3, 72.1, 71.6, 71.4, 70.2, 70.3, 70.5, 69.8][22.4, 22.2, 22.3, 22.0]How it works:
- The first comprehension computes one new value per reading, so the result has the same length.
- The second comprehension keeps each reading unchanged, but only when the condition is
True. all(...)isTruewhen every value passes the test; the assert uses it.
Alternative: the loop version needs an empty list and append() in a loop. The comprehension says the same in one line.
M04-W09 · Fix the bug: an empty set
Section titled “M04-W09 · Fix the bug: an empty set”Fix the bug: this code should collect the distinct tags of the first five customers. It crashes on the first add().
tags = {} # TODO: fix this linefor c in customers[:5]: for tag in c["tags"]: tags.add(tag)print(sorted(tags))The fixed code prints:
['loyalty', 'mobile_app', 'newsletter', 'referral', 'student', 'vip']Hint 1
Run print(type({})).
Hint 2
There is no literal for an empty set. Call the type: set().
Solution
tags = set()for c in customers[:5]: for tag in c["tags"]: tags.add(tag)print(sorted(tags))assert "vip" in tagsassert len(tags) == 6['loyalty', 'mobile_app', 'newsletter', 'referral', 'student', 'vip']How it works:
{}is an empty dict, which has noadd()method:AttributeError: 'dict' object has no attribute 'add'.set()makes an empty set.add()ignores tags that are already there.sorted()gives a stable order for the report.
Alternative: a set comprehension with two for parts does it in one line: {tag for c in customers[:5] for tag in c["tags"]}.
M04-C01 · Count customers per region
Section titled “M04-C01 · Count customers per region”Count the customers per region in data/customers.json. Print the regions in alphabetical order with their counts, then the total.
East 6North 7South 4West 3total 20region_counts = {}# TODO: count with region_counts.get(region, 0) + 1# TODO: print sorted by region, then the totalHint 1
The region sits in c["address"]["region"].
Hint 2
sorted(region_counts.items()) gives (region, count) pairs sorted by region. Unpack them in the loop.
Solution
region_counts = {}for c in customers: region = c["address"]["region"] region_counts[region] = region_counts.get(region, 0) + 1for region, count in sorted(region_counts.items()): print(f"{region:<6} {count:>2}")print("total ", sum(region_counts.values()))assert sum(region_counts.values()) == len(customers)assert set(region_counts) == {"East", "North", "South", "West"}East 6North 7South 4West 3total 20How it works:
region_counts.get(region, 0)returns 0 for a region the first time it appears.- Each record adds 1 to the count of its region.
sorted()on the items sorts the pairs by their first element, the region.- The total must equal the number of records. The assert proves it.
Alternative: collections.Counter(c["address"]["region"] for c in customers) counts in one line (module 09).
M04-C02 · Look up customers by id
Section titled “M04-C02 · Look up customers by id”Build a dict that maps each customer id to its record. Then print a one-line summary for the ids C00003, C00010 and C00012: name, city and number of orders. Finally, print whether C00099 exists.
C00003 Mei Chen San Francisco 5 ordersC00010 Noah Miller Atlanta 1 ordersC00012 Olivia Brown New York 0 ordersC00099 exists: False# TODO: by_id = {...}wanted = ["C00003", "C00010", "C00012"]# TODO: print a summary line per wanted id, then test C00099Hint 1
Map each id to its whole record with a dict comprehension. What goes left of the colon, and what goes right of it?
Hint 2
"C00099" in by_id tests the keys.
Solution
by_id = {c["customer_id"]: c for c in customers}wanted = ["C00003", "C00010", "C00012"]for cid in wanted: c = by_id[cid] print(f"{cid} {c['name']:<12} {c['address']['city']:<13} {len(c['orders'])} orders")print("C00099 exists:", "C00099" in by_id)assert len(by_id) == 20assert by_id["C00010"]["name"] == "Noah Miller"C00003 Mei Chen San Francisco 5 ordersC00010 Noah Miller Atlanta 1 ordersC00012 Olivia Brown New York 0 ordersC00099 exists: FalseHow it works:
- The comprehension maps each id to the record dict itself, not to a copy.
by_id[cid]finds a record in one step, whatever the number of customers.- Inside an f-string with double quotes, use single quotes for the keys:
c['name']. inon a dict tests the keys, so it answers “does this id exist?”.
Alternative: without the dict, you would scan the list each time: next(c for c in customers if c["customer_id"] == cid). That is per lookup.
M04-C03 · Interpret: missing, null or present?
Section titled “M04-C03 · Interpret: missing, null or present?”Interpret a result: the phone field of a customer record can be present with a value, present with null (Python None) or absent. Count the three cases. Then explain why c.get("phone") is None cannot tell the last two apart.
present: 6 | null: 1 | absent: 13null: ['C00010']get() is None: 14present, null, absent = [], [], []# TODO: sort each customer id into one of the three lists# TODO: print the counts and the ids of the null caseHint 1
Test the key first: "phone" not in c means absent.
Hint 2
If the key is there, c["phone"] is None means null.
Solution
present, null, absent = [], [], []for c in customers: if "phone" not in c: absent.append(c["customer_id"]) elif c["phone"] is None: null.append(c["customer_id"]) else: present.append(c["customer_id"])print("present:", len(present), "| null:", len(null), "| absent:", len(absent))print("null:", null)print("get() is None:", sum(c.get("phone") is None for c in customers))assert len(present) + len(null) + len(absent) == 20assert null == ["C00010"]present: 6 | null: 1 | absent: 13null: ['C00010']get() is None: 14How it works:
"phone" not in cchecks the keys, so it catches the absent case first.- When the key exists,
is Noneseparates a JSONnullfrom a real number. c.get("phone")returnsNonefor both null and absent, so it counts 14: the 1 null plus the 13 absent.sum()ofboolvalues counts theTruevalues.
Interpretation: for a report on contact coverage, “no phone” is enough, and get() is the right tool. For a data-quality check, the difference matters: a null means the source system knows the field and has no value; an absent key may mean an older export format. Test with in when that distinction matters.
M04-C04 · Compare customer segments with sets
Section titled “M04-C04 · Compare customer segments with sets”Marketing wants four lists of customer ids from data/customers.json: VIP customers who also get the newsletter, VIP customers who do not, all distinct tags in use, and customers with no tags. Build a set of ids per tag, then answer with set operations.
vip and newsletter: ['C00003', 'C00015']vip, no newsletter: ['C00004', 'C00005', 'C00012', 'C00013', 'C00020']tags in use: ['loyalty', 'mobile_app', 'newsletter', 'referral', 'student', 'vip']untagged: ['C00002', 'C00008', 'C00010', 'C00016', 'C00018']vip = {c["customer_id"] for c in customers if "vip" in c["tags"]}# TODO: newsletter = ...# TODO: print the four answers (sorted)Hint 1
vip & newsletter is “in both”; vip - newsletter is “in the first only”.
Hint 2
All distinct tags: a set comprehension with two for parts. No tags: not c["tags"] is True for an empty list.
Solution
vip = {c["customer_id"] for c in customers if "vip" in c["tags"]}newsletter = {c["customer_id"] for c in customers if "newsletter" in c["tags"]}all_tags = {tag for c in customers for tag in c["tags"]}untagged = [c["customer_id"] for c in customers if not c["tags"]]print("vip and newsletter:", sorted(vip & newsletter))print("vip, no newsletter:", sorted(vip - newsletter))print("tags in use:", sorted(all_tags))print("untagged:", untagged)assert (vip & newsletter) | (vip - newsletter) == vipassert len(untagged) == 5vip and newsletter: ['C00003', 'C00015']vip, no newsletter: ['C00004', 'C00005', 'C00012', 'C00013', 'C00020']tags in use: ['loyalty', 'mobile_app', 'newsletter', 'referral', 'student', 'vip']untagged: ['C00002', 'C00008', 'C00010', 'C00016', 'C00018']How it works:
- Each set comprehension collects the ids that carry one tag.
&and-answer the two VIP questions without any loop.- The two-
forcomprehension flattens the tag lists of all customers into one set. - An empty list is falsy, so
not c["tags"]finds the untagged customers. - The first assert checks a law of set algebra: “both” plus “first only” gives the whole first set.
Alternative: if you need many tag questions, build a dict tag → set of ids once: {tag: {c["customer_id"] for c in customers if tag in c["tags"]} for tag in all_tags}.
M04-C05 · Refactor: loops to comprehensions
Section titled “M04-C05 · Refactor: loops to comprehensions”Refactor: the code below works. Rewrite each of its three loops as one comprehension, with the same results.
raw = ["21.0", "21.9", "21.4", "21.7", "22.1", "22.0", "22.5", "22.9", "22.2", "22.9", "22.7", "error", "22.4"]
valid = []for text in raw: if text != "error": valid.append(float(text))
labels = []for value in valid: if value >= 22.5: labels.append("alert") else: labels.append("ok")
plan_of = {}for c in customers: if c["plan"] != "basic": plan_of[c["customer_id"]] = c["plan"]
print(len(valid), valid[:4])print(labels.count("alert"), labels[6:9])print(len(plan_of), list(plan_of.items())[:2])# TODO: rewrite the three loops as comprehensions12 [21.0, 21.9, 21.4, 21.7]4 ['alert', 'alert', 'ok']13 [('C00001', 'premium'), ('C00002', 'standard')]Hint 1
A filter loop becomes [expr for x in items if cond].
Hint 2
An if/else that chooses a value is a conditional expression, a if cond else b, and it goes at the front of the comprehension, not at the end.
Hint 3
The dict loop becomes {key: value for c in customers if cond}.
Solution
raw = ["21.0", "21.9", "21.4", "21.7", "22.1", "22.0", "22.5", "22.9", "22.2", "22.9", "22.7", "error", "22.4"]
valid = [float(text) for text in raw if text != "error"]labels = ["alert" if value >= 22.5 else "ok" for value in valid]plan_of = {c["customer_id"]: c["plan"] for c in customers if c["plan"] != "basic"}
print(len(valid), valid[:4])print(labels.count("alert"), labels[6:9])print(len(plan_of), list(plan_of.items())[:2])assert len(labels) == len(valid) == 12assert "basic" not in plan_of.values()12 [21.0, 21.9, 21.4, 21.7]4 ['alert', 'alert', 'ok']13 [('C00001', 'premium'), ('C00002', 'standard')]How it works:
- The filter
if text != "error"moves to the end of the list comprehension. - The
if/elsebecomes a conditional expression at the front. It chooses a label for every value, so nothing is filtered out. - The dict loop becomes a dict comprehension with a filter.
- The three
print()lines are unchanged, so the output proves that the refactor kept the behavior.
Alternative: keep a loop when each step needs more than one line, a print() or error handling. A refactor is good only if the new code is easier to read.
M04-C06 · Fix the bug: a sale that changes the catalog
Section titled “M04-C06 · Fix the bug: a sale that changes the catalog”Fix the bug: a shop makes a 20% sale version of three Sports products (prices from data/products.csv). After the sale is prepared, the regular catalog shows the sale prices too.
catalog = [ {"product_id": "P016", "product": "Trail Running Shoes", "unit_price": 129.99}, {"product_id": "P017", "product": "Non-Slip Yoga Mat", "unit_price": 34.99}, {"product_id": "P018", "product": "Adjustable Dumbbells", "unit_price": 279.0},]sale = list(catalog) # TODO: this "copy" is the bugfor item in sale: item["unit_price"] = round(item["unit_price"] * 0.8, 2)print("catalog:", [p["unit_price"] for p in catalog])print("sale: ", [p["unit_price"] for p in sale])The fixed code prints:
catalog: [129.99, 34.99, 279.0]sale: [103.99, 27.99, 223.2]Hint 1
list(catalog) makes a new outer list. What about the dicts inside it?
Hint 2
Use copy.deepcopy(catalog), or build new dicts: {**p, "unit_price": ...}.
Solution
catalog = [ {"product_id": "P016", "product": "Trail Running Shoes", "unit_price": 129.99}, {"product_id": "P017", "product": "Non-Slip Yoga Mat", "unit_price": 34.99}, {"product_id": "P018", "product": "Adjustable Dumbbells", "unit_price": 279.0},]sale = copy.deepcopy(catalog)for item in sale: item["unit_price"] = round(item["unit_price"] * 0.8, 2)print("catalog:", [p["unit_price"] for p in catalog])print("sale: ", [p["unit_price"] for p in sale])assert catalog[0]["unit_price"] == 129.99assert sale[0] is not catalog[0]catalog: [129.99, 34.99, 279.0]sale: [103.99, 27.99, 223.2]How it works:
list(catalog)is a shallow copy. The new list holds the same three dicts, so changing a price insalechanges the catalog.copy.deepcopy()copies the list and each dict. The sale loop now changes only the copies.- The
is notassert proves that the records are separate objects.
Alternative: build the sale records directly, without changing anything. {**p, "unit_price": ...} copies the items of p into a new dict and overrides one key:
catalog = [ {"product_id": "P016", "product": "Trail Running Shoes", "unit_price": 129.99}, {"product_id": "P017", "product": "Non-Slip Yoga Mat", "unit_price": 34.99},]sale = [{**p, "unit_price": round(p["unit_price"] * 0.8, 2)} for p in catalog]print([p["unit_price"] for p in catalog], [p["unit_price"] for p in sale])[129.99, 34.99] [103.99, 27.99]This works here because every value of the records is immutable. With a nested list or dict inside, {**p} would share it, as any shallow copy does.
M04-C07 · Turn records into columns
Section titled “M04-C07 · Turn records into columns”Five Electronics products from data/products.csv are stored as records (a list of dicts). Turn them into columns (a dict of lists) with a comprehension. Then use the columns to print the mean price and the margin rate of each product: (price − cost) ÷ price.
['product_id', 'unit_cost', 'unit_price']mean price: 595.40{'P001': 0.606, 'P002': 0.582, 'P003': 0.349, 'P004': 0.321, 'P005': 0.56}records = [ {"product_id": "P001", "unit_cost": 31.5, "unit_price": 79.99}, {"product_id": "P002", "unit_cost": 104.0, "unit_price": 249.0}, {"product_id": "P003", "unit_cost": 845.0, "unit_price": 1299.0}, {"product_id": "P004", "unit_cost": 780.0, "unit_price": 1149.0}, {"product_id": "P005", "unit_cost": 88.0, "unit_price": 199.99},]# TODO: columns = {field: [...] for field in ...}# TODO: mean price and margin rates with zip()Hint 1
The field names are the keys of the first record: records[0] or list(records[0]).
Hint 2
zip(columns["unit_cost"], columns["unit_price"]) pairs the cost and price of each product.
Solution
records = [ {"product_id": "P001", "unit_cost": 31.5, "unit_price": 79.99}, {"product_id": "P002", "unit_cost": 104.0, "unit_price": 249.0}, {"product_id": "P003", "unit_cost": 845.0, "unit_price": 1299.0}, {"product_id": "P004", "unit_cost": 780.0, "unit_price": 1149.0}, {"product_id": "P005", "unit_cost": 88.0, "unit_price": 199.99},]columns = {field: [r[field] for r in records] for field in records[0]}prices = columns["unit_price"]rates = [round((p - c) / p, 3) for c, p in zip(columns["unit_cost"], prices)]print(list(columns))print(f"mean price: {sum(prices) / len(prices):.2f}")print(dict(zip(columns["product_id"], rates)))assert all(len(col) == len(records) for col in columns.values())assert rates[2] == 0.349['product_id', 'unit_cost', 'unit_price']mean price: 595.40{'P001': 0.606, 'P002': 0.582, 'P003': 0.349, 'P004': 0.321, 'P005': 0.56}How it works:
- A for loop over a dict gives its keys, so
for field in records[0]runs over the field names. - For each field, the inner comprehension collects that field from every record.
zip()walks the cost and price columns side by side. Each pair is unpacked intocandp.dict(zip(ids, rates))pairs each product id with its rate.
Alternative: in module 24, pd.DataFrame(records) does the reshaping, and (df.unit_price - df.unit_cost) / df.unit_price computes all the rates at once.
M04-C08 · Interpret: why deduplication gets slow
Section titled “M04-C08 · Interpret: why deduplication gets slow”Interpret a result: a pipeline removes duplicate order ids with a list: if oid not in seen: seen.append(oid). For unique ids, the k-th check scans the k ids seen so far. Count the comparisons for 1,000 and 10,000 ids, and for a set. Then explain the growth.
5 ids, counted: 10 formula: 10 1000 ids: list 499,500 comparisons, set 1,000 lookups 10000 ids: list 49,995,000 comparisons, set 10,000 lookups10x more ids -> 100x more list workseen = []counted = 0# TODO: loop over 5 unique order ids; before each check, add len(seen) to counted# TODO: compare counted with sum(range(5))# TODO: print the list comparisons and the set lookups for n = 1,000 and 10,000Hint 1
sum(range(n)) is 0 + 1 + … + (n − 1).
Hint 2
Check the formula on a small case by counting for real: loop over 5 ids and add len(seen) before each append.
Solution
seen = []counted = 0for oid in ["O000001", "O000002", "O000003", "O000004", "O000005"]: counted += len(seen) # a miss scans every id seen so far if oid not in seen: seen.append(oid)print("5 ids, counted:", counted, "formula:", sum(range(5)))
for n in [1_000, 10_000]: print(f"{n:>6} ids: list {sum(range(n)):>10,} comparisons, set {n:>6,} lookups")growth = sum(range(10_000)) / sum(range(1_000))print(f"10x more ids -> {growth:.0f}x more list work")assert counted == sum(range(5)) == 10assert round(growth) == 1005 ids, counted: 10 formula: 10 1000 ids: list 499,500 comparisons, set 1,000 lookups 10000 ids: list 49,995,000 comparisons, set 10,000 lookups10x more ids -> 100x more list workHow it works:
- For a new id,
oid not in seencompares it with every id inseen. The k-th id costs k − 1 comparisons. - The total is 0 + 1 + … + (n − 1) = n(n − 1) / 2, about n² / 2. The small loop confirms the formula for 5 ids.
- A set lookup costs one hash per id, so the work is about n.
Interpretation: the list method is quadratic, . Ten times more ids means about a hundred times more work. At 1 million ids, that is 500 billion comparisons, which takes hours. A set keeps it linear: replace seen = [] with seen = set() and append with add. If the order of first appearance matters, use list(dict.fromkeys(ids)).
M04-C09 · Choose and justify: four structures for four jobs
Section titled “M04-C09 · Choose and justify: four structures for four jobs”Choose a method and justify it: pick a list, tuple, dict or set for each job, build it and run the operation. Use the data in the starter.
- Find the price of a product by its id.
- Keep the hourly temperatures of sensor S1 in time order (duplicates allowed).
- Find which of today’s order emails are new, given the emails seen before.
- Store a store’s location as a fixed pair and use it as a key for the store id.
1. 299.992. 19.95 coldest hour: 33. ['tom.becker@example.com']4. S01price_rows = [("P006", 349.0), ("P007", 299.99), ("P008", 129.95)]hourly = [20.21, 20.11, 19.46, 19.13, 19.95] # S1, 00:00 to 04:00seen_before = ["ana.silva@example.com", "mei.chen@example.com"]today = ["mei.chen@example.com", "tom.becker@example.com", "ana.silva@example.com"]# TODO: 1. prices = ... 2. readings = ... 3. new emails 4. store_at = {...}Hint 1
Ask for each job: will I look up by key, keep order, test membership, or need a fixed hashable value?
Hint 2
dict(price_rows) turns a list of pairs into a dict. A list comprehension with not in seen filters today’s emails.
Solution
price_rows = [("P006", 349.0), ("P007", 299.99), ("P008", 129.95)]hourly = [20.21, 20.11, 19.46, 19.13, 19.95] # S1, 00:00 to 04:00seen_before = ["ana.silva@example.com", "mei.chen@example.com"]today = ["mei.chen@example.com", "tom.becker@example.com", "ana.silva@example.com"]
prices = dict(price_rows) # 1. dict: lookup by keyreadings = list(hourly) # 2. list: order and duplicatesseen = set(seen_before) # 3. set: fast "seen before?"new_emails = [e for e in today if e not in seen]store_at = {(41.88, -87.63): "S01"} # 4. tuple: fixed and hashable
print("1.", prices["P007"])print("2.", readings[-1], "coldest hour:", readings.index(min(readings)))print("3.", new_emails)print("4.", store_at[(41.88, -87.63)])assert isinstance(prices, dict) and isinstance(seen, set)assert new_emails == ["tom.becker@example.com"]1. 299.992. 19.95 coldest hour: 33. ['tom.becker@example.com']4. S01How it works:
- dict for prices:
prices["P007"]is one lookup. A list of pairs would need a scan. - list for the readings: the position is the hour, so
index()of the minimum gives the coldest hour. Two equal readings would both stay. A set would lose the order and the duplicates. - set for the seen emails: each
intest is , so the check stays fast with a million known emails. The result stays a list to keep today’s order. - tuple for the coordinates: a pair of floats that never changes, and hashable, so it can be a key. A list would raise
TypeError: unhashable type: 'list'.
Alternative: for job 3, set(today) - seen also finds the new emails, but it loses the order and the duplicates of today’s list. Choose it when only “which ones” matters.
M04-C10 · Group readings by sensor
Section titled “M04-C10 · Group readings by sensor”The first twelve rows of data/sensors.csv hold three timestamps for sensors S1 to S4. Group the temperatures by sensor in a dict of lists, then print each sensor’s readings and mean, and the warmest sensor.
S1: [20.21, 20.22, 20.16] mean 20.20S2: [22.3, 22.44, 22.25] mean 22.33S3: [19.4, 19.46, 19.54] mean 19.47S4: [24.52, 24.63, 24.73] mean 24.63warmest: S4rows = [ ("00:00", "S1", 20.21), ("00:00", "S2", 22.3), ("00:00", "S3", 19.4), ("00:00", "S4", 24.52), ("00:10", "S1", 20.22), ("00:10", "S2", 22.44), ("00:10", "S3", 19.46), ("00:10", "S4", 24.63), ("00:20", "S1", 20.16), ("00:20", "S2", 22.25), ("00:20", "S3", 19.54), ("00:20", "S4", 24.73),]by_sensor = {}# TODO: group with setdefault, then print the meansHint 1
Which dict method returns the list for a key and creates an empty one the first time the key appears?
Hint 2
d.setdefault(key, []) returns the list for key, so you can call .append(temp) on its result. For the warmest sensor, build a dict of means and use max(means, key=means.get).
Solution
rows = [ ("00:00", "S1", 20.21), ("00:00", "S2", 22.3), ("00:00", "S3", 19.4), ("00:00", "S4", 24.52), ("00:10", "S1", 20.22), ("00:10", "S2", 22.44), ("00:10", "S3", 19.46), ("00:10", "S4", 24.63), ("00:20", "S1", 20.16), ("00:20", "S2", 22.25), ("00:20", "S3", 19.54), ("00:20", "S4", 24.73),]by_sensor = {}for _, sensor, temp in rows: by_sensor.setdefault(sensor, []).append(temp)
means = {s: sum(temps) / len(temps) for s, temps in by_sensor.items()}for sensor, temps in by_sensor.items(): print(f"{sensor}: {temps} mean {means[sensor]:.2f}")print("warmest:", max(means, key=means.get))assert list(by_sensor) == ["S1", "S2", "S3", "S4"]assert all(len(t) == 3 for t in by_sensor.values())S1: [20.21, 20.22, 20.16] mean 20.20S2: [22.3, 22.44, 22.25] mean 22.33S3: [19.4, 19.46, 19.54] mean 19.47S4: [24.52, 24.63, 24.73] mean 24.63warmest: S4How it works:
- The loop unpacks each row and ignores the time with
_. setdefault()returns the list for the sensor, creating an empty one the first time.append()changes that list inside the dict.- The dict keeps insertion order, so the sensors print in the order they first appear.
max(means, key=means.get)compares the sensor ids by their mean temperature.
Alternative: collections.defaultdict(list) creates the empty list for you: by_sensor[sensor].append(temp) (module 09).
M04-C11 · Predict the output: a confusion matrix built with *
Section titled “M04-C11 · Predict the output: a confusion matrix built with *”Predict the output: a confusion matrix counts the predictions of a classifier. Row = the true class, column = the predicted class. This code builds a 2 × 2 matrix of zeros for a churn model (class 0 = stays, 1 = churns) and counts four predictions. Predict the matrix, then fix the code so that it counts correctly.
Acceptance criteria:
- Write your prediction of the first line, then run the code.
- After your fix, the matrix is
[[1, 1], [1, 1]]and the counts add up to 4.
matrix = [[0] * 2] * 2pairs = [(0, 0), (0, 1), (1, 0), (1, 1)] # (true class, predicted class)for true_class, predicted in pairs: matrix[true_class][predicted] += 1print(matrix)# TODO: predict the output, then fix the first lineHint 1
[row] * 2 repeats the reference to row. How many inner lists exist?
Hint 2
Make a new inner list for each row with a comprehension: [[0] * 2 for _ in range(2)].
Solution
matrix = [[0] * 2] * 2pairs = [(0, 0), (0, 1), (1, 0), (1, 1)] # (true class, predicted class)for true_class, predicted in pairs: matrix[true_class][predicted] += 1print("buggy:", matrix, matrix[0] is matrix[1])
matrix = [[0] * 2 for _ in range(2)]for true_class, predicted in pairs: matrix[true_class][predicted] += 1print("fixed:", matrix, matrix[0] is matrix[1])assert matrix == [[1, 1], [1, 1]]assert sum(sum(row) for row in matrix) == len(pairs)buggy: [[2, 2], [2, 2]] Truefixed: [[1, 1], [1, 1]] FalseHow it works:
[0] * 2builds one list[0, 0]. Multiplying the outer list by 2 copies the reference, so both rows are the same list.- Every count goes into that one list, and both rows show
[2, 2]. The total looks like 8, although there are only 4 predictions. - The comprehension runs
[0] * 2once per row, so each row is a new list. [0] * 2itself is safe: the zeros are immutableintvalues.
Alternative: sklearn.metrics.confusion_matrix(y_true, y_pred) builds this matrix for you (module 36). NumPy’s np.zeros((2, 2), dtype=int) makes a real 2-D array with no shared rows.
M04-C12 · Filter and invert a price table
Section titled “M04-C12 · Filter and invert a price table”The Home category of data/products.csv has five products. Build a dict of product id → price, keep only the products above 150, then invert a dict of id → name into name → id to find the id of the “Robot Vacuum”.
{'P006': 349.0, 'P007': 299.99, 'P009': 189.0}P007mean Home price: 207.59home = [ ("P006", "Espresso Machine", 349.0), ("P007", "Robot Vacuum", 299.99), ("P008", "Chef's Knife Set", 129.95), ("P009", "Air Purifier", 189.0), ("P010", "Cotton Bed Sheet Set", 69.99),]# TODO: price_of, expensive, name_of, id_ofHint 1
Unpack each tuple into three names in the for part of a dict comprehension. Use _ for the field you do not need.
Hint 2
To invert a dict, loop over its items() and swap the roles: the old value becomes the new key.
Solution
home = [ ("P006", "Espresso Machine", 349.0), ("P007", "Robot Vacuum", 299.99), ("P008", "Chef's Knife Set", 129.95), ("P009", "Air Purifier", 189.0), ("P010", "Cotton Bed Sheet Set", 69.99),]price_of = {pid: price for pid, _, price in home}expensive = {pid: price for pid, price in price_of.items() if price > 150}name_of = {pid: name for pid, name, _ in home}id_of = {name: pid for pid, name in name_of.items()}print(expensive)print(id_of["Robot Vacuum"])print(f"mean Home price: {sum(price_of.values()) / len(price_of):.2f}")assert len(id_of) == len(name_of)assert set(expensive) <= set(price_of){'P006': 349.0, 'P007': 299.99, 'P009': 189.0}P007mean Home price: 207.59How it works:
- Unpacking in the comprehension names the three fields and ignores the one that is not needed.
- The filter
if price > 150keeps three of the five items. - Inverting swaps the roles of key and value. It is safe here because the names are unique.
- The first assert would catch duplicate names: an inverted dict silently keeps only the last one.
Alternative: dict(zip(names, ids)) inverts when you have two parallel lists.
M04-C13 · Rank customers by average order value
Section titled “M04-C13 · Rank customers by average order value”The average order value of a customer is the total order amount divided by the number of orders. Compute it for every customer in data/customers.json who has at least one order, with a dict comprehension. Print the three highest values with the order counts, and the number of customers you had to leave out.
1. C00017 1,162.49 orders: 22. C00007 483.30 orders: 13. C00015 455.09 orders: 3left out (no orders): 3# TODO: aov = {customer_id: average order amount}, only for customers with orders# TODO: rank (value, id) tuples in reverse and print the top 3 with the order counts# TODO: count the customers that are not in aovHint 1
Which customers would make the division fail? Filter them out at the end of the comprehension.
Hint 2
Tuples sort by their first element. Build (value, cid) pairs and sort them with reverse=True.
Hint 3
A lookup dict {c["customer_id"]: c for c in customers} gives you the order count of a ranked id.
Solution
aov = { c["customer_id"]: sum(o["amount"] for o in c["orders"]) / len(c["orders"]) for c in customers if c["orders"]}by_id = {c["customer_id"]: c for c in customers}ranking = sorted([(value, cid) for cid, value in aov.items()], reverse=True)for rank, (value, cid) in enumerate(ranking[:3], start=1): print(f"{rank}. {cid} {value:>9,.2f} orders: {len(by_id[cid]['orders'])}")print("left out (no orders):", len(customers) - len(aov))assert ranking[0][1] == "C00017"assert len(aov) == 171. C00017 1,162.49 orders: 22. C00007 483.30 orders: 13. C00015 455.09 orders: 3left out (no orders): 3How it works:
- The filter
if c["orders"]drops the customers with an empty order list. Without it,len(c["orders"])would be 0 and the division would raiseZeroDivisionError. - The generator expression feeds the amounts of one customer to
sum(). - Swapping each item to
(value, cid)makes the value the first thing thatsorted()compares. enumerate(..., start=1)numbers the ranks from 1, and the loop unpacks the nested tuple(rank, (value, cid)).
Interpretation: C00017 tops this ranking with only 2 orders, because one of them is large. A high average from few orders is unstable. Report the order count next to an average, as here.
Alternative: sorted(aov, key=aov.get, reverse=True)[:3] gives the top ids directly; module 05 explains key=.
Challenge
Section titled “Challenge”M04-X01 · Region revenue report
Section titled “M04-X01 · Region revenue report”Build a per-region report from data/customers.json: customers, orders, revenue and revenue per customer. Sort the regions by revenue, highest first. Use a dict of dicts for the totals.
region cust orders revenue per custNorth 7 18 5,097.14 728.16West 3 9 3,515.26 1,171.75East 6 10 2,900.85 483.47South 4 11 2,198.45 549.61report = {}# TODO: for each customer, add to report[region]: customers, orders, revenue# TODO: sort the regions by revenue and print the tableHint 1
report.setdefault(region, {"customers": 0, "orders": 0, "revenue": 0.0}) gives the totals dict for a region.
Hint 2
Sort (revenue, region) tuples in reverse to rank the regions.
Hint 3
Print a header with the same format specs as the rows, for example f"{'region':<6} {'cust':>4} ...".
Solution
report = {}for c in customers: region = c["address"]["region"] totals = report.setdefault(region, {"customers": 0, "orders": 0, "revenue": 0.0}) totals["customers"] += 1 totals["orders"] += len(c["orders"]) totals["revenue"] += sum(o["amount"] for o in c["orders"])
ranked = sorted([(t["revenue"], region) for region, t in report.items()], reverse=True)print(f"{'region':<6} {'cust':>4} {'orders':>6} {'revenue':>10} {'per cust':>9}")for revenue, region in ranked: t = report[region] per_customer = revenue / t["customers"] print(f"{region:<6} {t['customers']:>4} {t['orders']:>6} {revenue:>10,.2f}" f" {per_customer:>9,.2f}")
assert sum(t["customers"] for t in report.values()) == 20assert sum(t["orders"] for t in report.values()) == 48region cust orders revenue per custNorth 7 18 5,097.14 728.16West 3 9 3,515.26 1,171.75East 6 10 2,900.85 483.47South 4 11 2,198.45 549.61How it works:
setdefault()returns the totals dict of the region and creates it the first time.totalsis an alias of the dict insidereport, so+=on its keys updates the report.- Each customer adds 1 customer, its order count and its order amounts.
(revenue, region)tuples sort by revenue first.reverse=Trueputs the highest first.- The asserts check the totals against the known counts of the file: 20 customers and 48 orders.
Alternative: keep the per-region totals as three separate dicts (customers_by_region, orders_by_region, …). That works, but a dict of dicts keeps the numbers of one region together, like a row of a table.
M04-X02 · Compare two versions of a config file
Section titled “M04-X02 · Compare two versions of a config file”data/config.json holds the settings of the sales pipeline. A colleague proposes a new version. Write a diff that prints the top-level keys that were added and removed, and, for the thresholds section, every key whose value changed, as key: old -> new.
added: ['alerts']removed: ['retry']thresholds.max_discount: 0.2 -> 0.25thresholds.max_quantity: 50 -> 30thresholds added: ['min_rows']with open("data/config.json", encoding="utf-8") as f: old = json.load(f)
new = copy.deepcopy(old)del new["retry"]new["alerts"] = {"email": "data-team@example.com"}new["thresholds"]["max_quantity"] = 30new["thresholds"]["max_discount"] = 0.25new["thresholds"]["min_rows"] = 100# TODO: added and removed top-level keys (set operations on the keys)# TODO: changed, added and removed keys inside "thresholds"Hint 1
old.keys() behaves like a set: new.keys() - old.keys() gives the added keys.
Hint 2
Changed keys are in both versions with different values: loop over sorted(a.keys() & b.keys()) and compare.
Hint 3
Check that old is unchanged at the end. Why does new need a deep copy?
Solution
with open("data/config.json", encoding="utf-8") as f: old = json.load(f)
new = copy.deepcopy(old)del new["retry"]new["alerts"] = {"email": "data-team@example.com"}new["thresholds"]["max_quantity"] = 30new["thresholds"]["max_discount"] = 0.25new["thresholds"]["min_rows"] = 100
print("added:", sorted(new.keys() - old.keys()))print("removed:", sorted(old.keys() - new.keys()))a, b = old["thresholds"], new["thresholds"]changed = {k: (a[k], b[k]) for k in sorted(a.keys() & b.keys()) if a[k] != b[k]}for key, (before, after) in changed.items(): print(f"thresholds.{key}: {before} -> {after}")print("thresholds added:", sorted(b.keys() - a.keys()))assert old["thresholds"]["max_quantity"] == 50assert "retry" in oldadded: ['alerts']removed: ['retry']thresholds.max_discount: 0.2 -> 0.25thresholds.max_quantity: 50 -> 30thresholds added: ['min_rows']How it works:
- The
keys()view of a dict supports-,&and|, like a set. Differences give the added and removed keys. - The keys in both versions are the intersection. A dict comprehension keeps those whose values differ, as
(old, new)tuples. - The loop unpacks each item into the key and the nested tuple.
newwas built withcopy.deepcopy(). A shallow copy would share thethresholdsdict, so the changes would appear inoldtoo, and the diff would find no changed thresholds at all.
Alternative: for a full recursive diff of nested configs, write a function that calls itself on nested dicts (recursion, module 05). Tools such as git diff do this for text files.
M04-X03 · Build a feature table without touching the source
Section titled “M04-X03 · Build a feature table without touching the source”Prepare the customer records for a churn model. For each customer, build a new record with the id, the plan, the region, the number of orders, the total spend, the number of tags and a 0/1 flag for the vip tag. Drop names, emails and phone numbers. The original records must stay unchanged; prove it by comparing them with a fresh load of the file.
['customer_id', 'plan', 'region', 'n_orders', 'total_spend', 'n_tags', 'is_vip']['C00001', 'premium', 'North', 5, 1325.54, 2, 0]['C00002', 'standard', 'West', 3, 961.89, 0, 0]20 records, 7 fieldssource unchanged: True# TODO: features = [ {...} for c in customers ]# TODO: print the field names, the values of the first two records, the counts# TODO: compare customers with a fresh json.load of the fileHint 1
Build each new record with a dict literal inside a list comprehension. Read from c, never assign into it.
Hint 2
int("vip" in c["tags"]) turns True/False into 1/0.
Hint 3
Two lists of dicts are equal with == when every record has equal keys and values.
Solution
features = [ { "customer_id": c["customer_id"], "plan": c["plan"], "region": c["address"]["region"], "n_orders": len(c["orders"]), "total_spend": round(sum(o["amount"] for o in c["orders"]), 2), "n_tags": len(c["tags"]), "is_vip": int("vip" in c["tags"]), } for c in customers]print(list(features[0]))print(list(features[0].values()))print(list(features[1].values()))print(len(features), "records,", len(features[0]), "fields")
with open("data/customers.json", encoding="utf-8") as f: fresh = json.load(f)["customers"]print("source unchanged:", customers == fresh)pii = {"name", "email", "phone"}assert all(pii.isdisjoint(row) for row in features)assert sum(row["is_vip"] for row in features) == 7['customer_id', 'plan', 'region', 'n_orders', 'total_spend', 'n_tags', 'is_vip']['C00001', 'premium', 'North', 5, 1325.54, 2, 0]['C00002', 'standard', 'West', 3, 961.89, 0, 0]20 records, 7 fieldssource unchanged: TrueHow it works:
- The comprehension builds a brand-new dict per customer. It only reads from the source, so no copy is needed.
- Nested values (the region, the order amounts, the tags) are turned into plain numbers and strings. The new records share no mutable object with the source.
customers == freshcompares the whole nested structure with a new load of the file.Trueproves that nothing changed.pii.isdisjoint(row)checks that no personal field name is a key of the feature record.
Alternative: copy.deepcopy(customers) followed by del and new keys also works. Building new records is usually clearer: the code lists exactly the fields that leave the system, which is what a privacy review wants to see.
M04-X04 · Count sensor statuses in the full file
Section titled “M04-X04 · Count sensor statuses in the full file”data/sensors.csv has 8,064 rows. Read its lines, then count the statuses per sensor in a nested dict {sensor: {status: count}}. Print one line per sensor and the sensors that ever reported fail. Reading a text file line by line uses the same with open(...) line as the JSON setup.
['timestamp', 'sensor_id', 'temperature_c', 'humidity_pct', 'vibration_mm_s', 'status']S1 ok=2002 warn=14 fail=0S2 ok=1994 warn=17 fail=5S3 ok=1994 warn=22 fail=0S4 ok=1597 warn=400 fail=19ever failed: ['S2', 'S4']with open("data/sensors.csv", encoding="utf-8") as f: header, *lines = f.read().splitlines()counts = {}# TODO: split each line on ",", unpack the six fields, count status per sensor# TODO: print the counts per sensor and the set of sensors with "fail"Hint 1
line.split(",") returns six strings. Unpack them: ts, sensor, temp, humidity, vibration, status = ....
Hint 2
per_sensor = counts.setdefault(sensor, {}), then count with per_sensor.get(status, 0) + 1.
Hint 3
Sensors with a failure: a set comprehension over counts.items() with if "fail" in statuses.
Solution
with open("data/sensors.csv", encoding="utf-8") as f: header, *lines = f.read().splitlines()print(header.split(","))
counts = {}for line in lines: _, sensor, _, _, _, status = line.split(",") per_sensor = counts.setdefault(sensor, {}) per_sensor[status] = per_sensor.get(status, 0) + 1
for sensor in sorted(counts): statuses = counts[sensor] parts = [f"{s}={statuses.get(s, 0)}" for s in ("ok", "warn", "fail")] print(sensor, " ".join(parts))failing = {sensor for sensor, statuses in counts.items() if "fail" in statuses}print("ever failed:", sorted(failing))assert len(lines) == 8064assert sum(sum(s.values()) for s in counts.values()) == len(lines)['timestamp', 'sensor_id', 'temperature_c', 'humidity_pct', 'vibration_mm_s', 'status']S1 ok=2002 warn=14 fail=0S2 ok=1994 warn=17 fail=5S3 ok=1994 warn=22 fail=0S4 ok=1597 warn=400 fail=19ever failed: ['S2', 'S4']How it works:
splitlines()returns a list of lines. Star-unpacking separates the header from the 8,064 data lines.- Each line splits into six strings. Unpacking keeps the sensor and the status and ignores the rest with
_. setdefault(sensor, {})returns the inner dict of the sensor. Counting into it updates the nested structure.- Printing the statuses in a fixed order (
ok,warn,fail) withget(s, 0)shows a 0 for a status that never appeared. - The last assert checks that every line was counted once.
Alternative: a dict with tuple keys, counts[(sensor, status)], is a flat version of the same table. The nested dict is easier when you ask “everything about one sensor”. Module 07 reads CSV files with the csv module, which handles quoted fields; split(",") is safe here only because the file has no commas inside values.
M04-X05 · Refactor: parallel lists to records
Section titled “M04-X05 · Refactor: parallel lists to records”Refactor: this report keeps the Books products of data/products.csv in three parallel lists. To rank by price, someone sorted the price list on its own. The ranking now pairs titles with the wrong prices. Rewrite the data as one list of tuples, sort the records, and add a dict lookup by id.
ids = ["P021", "P022", "P023", "P024", "P025"]titles = ["Harbor Lane Mysteries", "Weeknight Kitchen Cookbook", "A Brief History of Maps", "Statistics Made Simple", "The Mindful Runner"]prices = [16.99, 29.99, 24.5, 34.99, 14.99]prices.sort(reverse=True) # the bug: titles and ids are not reorderedfor i in range(len(ids)): print(ids[i], titles[i], prices[i])# TODO: one list of (price, id, title) tuples, sorted; then a dict by idP024 Statistics Made Simple 34.99P022 Weeknight Kitchen Cookbook 29.99P023 A Brief History of Maps 24.50P021 Harbor Lane Mysteries 16.99P025 The Mindful Runner 14.99P024: Statistics Made Simple 34.99Hint 1
Which built-in function ties the three lists together, one tuple per product? In which position must the price be for sorted() to compare prices?
Hint 2
zip(prices, ids, titles) builds the records. For the lookup, unpack each record in a dict comprehension and map the id to a (title, price) tuple.
Solution
ids = ["P021", "P022", "P023", "P024", "P025"]titles = ["Harbor Lane Mysteries", "Weeknight Kitchen Cookbook", "A Brief History of Maps", "Statistics Made Simple", "The Mindful Runner"]prices = [16.99, 29.99, 24.5, 34.99, 14.99]
records = sorted(zip(prices, ids, titles), reverse=True)for price, pid, title in records: print(f"{pid} {title:<27} {price:>6.2f}")book = {pid: (title, price) for price, pid, title in records}title, price = book["P024"]print("P024:", title, price)assert records[0][1] == "P024"assert book["P021"] == ("Harbor Lane Mysteries", 16.99)P024 Statistics Made Simple 34.99P022 Weeknight Kitchen Cookbook 29.99P023 A Brief History of Maps 24.50P021 Harbor Lane Mysteries 16.99P025 The Mindful Runner 14.99P024: Statistics Made Simple 34.99How it works:
zip()ties each price to its id and title once. Every later step moves whole records, so the fields can never drift apart.- Tuples sort by their first element, the price.
reverse=Trueputs the most expensive book first. - The dict comprehension builds an id →
(title, price)lookup from the same records. - The asserts check that the ranking and the lookup agree with the source data.
Alternative: a list of dicts ({"id": ..., "title": ..., "price": ...}) names the fields instead of relying on positions. Sorting it needs key=, which module 05 explains; module 21 replaces such records with dataclasses.
M04-X06 · Fix the bugs: a cleaning step that skips values
Section titled “M04-X06 · Fix the bugs: a cleaning step that skips values”Fix the bugs: a gateway sends a batch of raw readings with gaps. The cleaning step should drop every invalid value, keep the raw batch unchanged for the audit log and count the dropped values. It has two bugs: some invalid values survive, and the “raw” batch is damaged.
batch = ["21.2", "n/a", "", "21.0", "error", "error", "20.1"]raw_for_audit = batch # TODO: bug 2for value in batch: # TODO: bug 1 if not value.replace(".", "", 1).isdigit(): batch.remove(value)cleaned = [float(v) for v in batch]print("cleaned:", cleaned)print("raw kept:", raw_for_audit)print("dropped:", len(raw_for_audit) - len(cleaned))cleaned: [21.2, 21.0, 20.1]raw kept: ['21.2', 'n/a', '', '21.0', 'error', 'error', '20.1']dropped: 4Hint 1
Run the starter with print(value) inside the loop. Which values does the loop never visit?
Hint 2
Removing an element shifts the later elements one position to the left, but the loop still moves on to the next position.
Hint 3
Do not change the list you loop over. Build a new list with a comprehension, and keep the raw batch as a copy, or simply never change it.
Solution
batch = ["21.2", "n/a", "", "21.0", "error", "error", "20.1"]raw_for_audit = batch.copy()cleaned = [float(v) for v in batch if v.replace(".", "", 1).isdigit()]print("cleaned:", cleaned)print("raw kept:", raw_for_audit)print("dropped:", len(raw_for_audit) - len(cleaned))assert cleaned == [21.2, 21.0, 20.1]assert raw_for_audit == ["21.2", "n/a", "", "21.0", "error", "error", "20.1"]cleaned: [21.2, 21.0, 20.1]raw kept: ['21.2', 'n/a', '', '21.0', 'error', 'error', '20.1']dropped: 4How it works:
- Bug 1: the loop walks positions 0, 1, 2, …. When it removes
"n/a"at position 1,""moves into position 1, and the loop goes on to position 2. So""is never checked, and neither is the second"error". The starter then crashes infloat(""). - The fix builds a new list with a comprehension. Nothing changes while the loop runs.
- Bug 2:
raw_for_audit = batchis an alias. Any change tobatchdamages the audit copy.batch.copy()makes a real copy of this list of strings. With the comprehension,batchis no longer changed at all, but the copy keeps the audit log safe if a later step changesbatch. - 7 raw values minus 3 clean values: 4 dropped.
Alternative: if you must change the list in place, for example because other code holds a reference to it, assign to a full slice: batch[:] = [v for v in batch if ...]. That replaces the content of the same list object.