04. Data structures — Mini-project
You join the data team of an online shop. The CRM (customer relationship management) system exports its customer records as JSON every night. Before anyone builds a churn model on this export, your lead asks for a data audit: a check of the data’s consistency and completeness, with a short report. It answers five questions.
- Is the export consistent? Are the customer ids, the emails and the order ids unique? Is the
countfield right? Is any order dated before the customer signed up? - How complete is it? Which customers lack a postal code or a phone number, and which lack both?
- Is the geography plausible? Every customer’s city should be a store city of the customer’s region.
- How are the orders spread over time, and how big are they?
- Can we share it? Build a pseudonymized copy for an outside analytics partner, without damaging the source records.
Write a script, customer_audit.py, that prints the report below. The project uses every part of module 04: lists, tuples, dicts, sets, nested structures, unpacking, comprehensions, aliasing and copies, and the choice of the right structure for each question. The exercises counted plans, tags and spend; this audit asks new questions of the same records.
Dataset
Section titled “Dataset”data/customers.json holds one JSON object with three keys:
| Key | Type in Python | Content |
|---|---|---|
exported_at |
str |
the export time, "2025-01-02T06:00:00Z" |
count |
int |
the number of records the system says it exported |
customers |
list of dict |
the 20 customer records C00001 to C00020 |
Each customer record has these keys:
| Key | Type | Notes |
|---|---|---|
customer_id |
str |
C00001 … C00020 |
name, email |
str |
personal data: must not leave the company |
signup_date, plan |
str |
plan is basic, standard or premium |
address |
dict |
street, city, region and usually postal_code |
tags |
list of str |
sorted; can be empty |
orders |
list of dict |
each with order_id, date, items and amount; can be empty |
phone |
str or None |
personal data; absent from most records |
The stores of data/stores.csv give the valid cities per region:
| Region | Store cities |
|---|---|
| North | Chicago, Minneapolis, Detroit |
| South | Houston, Atlanta, Miami |
| East | New York, Boston, Philadelphia |
| West | Seattle, San Francisco, Denver |
Load the export with the two lines from the lesson:
import json
with open("data/customers.json", encoding="utf-8") as f: export = json.load(f)Requirements
Section titled “Requirements”Your script must:
- Load the export and keep the records in a list named
customers. Never change these records. - Consistency: check that
countequals the number of records, and that the customer ids, the emails and the order ids are unique. Use sets. Flatten the orders into tuples(customer_id, order_id, date, items, amount)and count the orders dated before their customer’ssignup_date. ISO dates (YYYY-MM-DD) compare correctly as strings. - Completeness: build a set of the ids without a postal code and a set of the ids without a phone (absent or
null). Print the size of their union and the ids in their intersection. - Geography: store the table above as a dict of sets, region → store cities. Count the customers whose city is not a store city of their region, and list the store cities that have no customer in the export.
- Orders over time: count the orders per month (
"YYYY-MM") in a dict, derive the orders per year from it, and print the busiest month or months. Print the mean number of items per order and the largest order with its customer and date. - Revenue by plan: build a dict of dicts plan →
{"customers": …, "buyers": …, "revenue": …}. A buyer is a customer with at least one order. Print the revenue per customer for each plan. - Export: build a pseudonymized list of records without
name,emailandphone, whoseaddressholds only the region. Prove that the source records still contain their personal fields, and that no export record shares a mutable object with the source: not the record, the address, the tags, the order list or any order dict. - Print the report below exactly, and end with at least three
assertchecks.
The expected report:
Customer audit: 20 records, exported 2025-01-02T06:00:00Z==========================================================Consistency count field matches: True unique customer ids: True unique emails: True unique order ids: True (48 orders) orders before signup: 0Completeness no postal code: ['C00005', 'C00014'] no phone: 14 any gap: 14 both gaps: ['C00005', 'C00014']Geography city outside its region's store cities: 0 store cities without a customer: ['Boston', 'Detroit', 'Houston']Orders over time per year: {'2023': 34, '2024': 14} months with orders: 19 busiest month(s): 2023-05 (6 orders) items per order: 2.02 largest: O002016 by C00017 on 2023-05-22 (2,312.99)Revenue by plan basic 7 customers 7 buyers 5,629.30 804.19 per customer premium 6 customers 5 buyers 4,187.06 697.84 per customer standard 7 customers 5 buyers 3,895.34 556.48 per customerPseudonymized export fields: customer_id, signup_date, plan, address, tags, orders address fields: region source intact: True nothing shared: TrueStep plan
Section titled “Step plan”-
Load and look. Load the export. Print the keys of the top-level dict and of the first record and of its first order before you write any other code.
-
Flatten the orders. A list comprehension with two
forparts gives one tuple per order. Star-unpacking such asfor _, oid, *_ in orderspicks the fields you need. -
Consistency with sets.
len(set(ids)) == len(ids)isTruewhen no id repeats. For the signup check, build a lookup dict id →signup_datefirst. -
Completeness with set algebra.
|gives the customers with any gap,&those with both gaps.c.get("phone") is NoneisTruefor an absent and for anullphone. -
Geography.
city not in STORE_CITIES[region]is an test.set().union(*STORE_CITIES.values())merges the four sets; the star spreads them as arguments. -
Orders per month. Count with
per_month.get(month, 0) + 1, wheremonth = date[:7]. Then loop over the months to add them up per year. -
Revenue by plan. Use
setdefault()to create the inner dict of each plan the first time.bool(c["orders"])is 1 for a buyer when you add it. -
Pseudonymize. Use
copy.deepcopy()and then delete the personal fields that each record actually has. Replaceaddresswith a new one-key dict. Check the result withis noton every container, including each order dict. -
Print and assert. Format money with
:,.2f. Compare every line with the expected report.
A skeleton to start from:
# customer_audit.py: audit the nightly CRM export before modeling.import copyimport json
with open("data/customers.json", encoding="utf-8") as f: export = json.load(f)customers = export["customers"]
STORE_CITIES = { "North": {"Chicago", "Minneapolis", "Detroit"}, # TODO: South, East and West}
# --- 1. Consistency ---# TODO: flat order tuples; unique customer ids, emails and order ids; early orders
# --- 2. Completeness ---# TODO: set of ids without postal code, set without phone; union and intersection
# --- 3. Geography ---# TODO: customers outside their region's store cities; store cities without customers
# --- 4. Orders over time ---# TODO: orders per month and per year, busiest month, items per order, largest order
# --- 5. Revenue by plan ---# TODO: plan -> {"customers": ..., "buyers": ..., "revenue": ...}
# --- 6. Pseudonymized export ---# TODO: deep copy, remove personal fields, keep only the region; prove nothing is shared
# --- Self-checks ---# TODO: at least three assert statementsRubric
Section titled “Rubric”| Criterion | Points | Full points when |
|---|---|---|
| Runs as a script | 2 | python customer_audit.py runs with no error and prints the report |
| Correct numbers | 3 | Every value matches the expected report |
| Right structure per question | 3 | Sets for uniqueness and gaps, a dict of sets for the cities, dicts for counts, tuples for order rows |
| Nested access | 2 | Reads address, tags and orders safely, with in and get() where fields can be missing |
| Comprehensions and unpacking | 2 | Readable list, set and dict comprehensions; unpacking instead of row[1] |
| Safe export | 3 | The source records keep every field; the checks cover every shared container |
| Readability | 2 | Clear names and comments that explain each choice of structure |
| Self-checks | 1 | At least three meaningful assert statements |
| Total | 18 | 14 or more: you are ready for module 05 |
Stretch goals
Section titled “Stretch goals”- Add a check that every email equals
first.last@example.combuilt from the name. Lowercase the name and replace the space with a dot. - For each tag, print the mean spend of the customers with that tag. Use a dict tag → list of totals.
- Print the orders per quarter (
2023-Q1…). The quarter of monthmis(m - 1) // 3 + 1. - Turn the pseudonymized records into columns (a dict of lists), ready for
pd.DataFramein module 24. - Write the export to
output/customers_pseudonymized.jsonwithjson.dump(records, f, indent=2). Open the file in your editor and check it by eye.
Reference solution
Section titled “Reference solution”Try the project yourself first. Then compare your script with this one. Your names and comments can differ; your output must not.
Reference solution
# customer_audit.py: audit the nightly CRM export before modeling.import copyimport json
with open("data/customers.json", encoding="utf-8") as f: export = json.load(f)customers = export["customers"] # source records: read them, never change them
# Store cities per region, from data/stores.csv (a dict of sets: fast "in" tests)STORE_CITIES = { "North": {"Chicago", "Minneapolis", "Detroit"}, "South": {"Houston", "Atlanta", "Miami"}, "East": {"New York", "Boston", "Philadelphia"}, "West": {"Seattle", "San Francisco", "Denver"},}
# --- 1. Consistency: sets answer "is anything repeated?" ---------------ids = [c["customer_id"] for c in customers]emails = [c["email"] for c in customers]# One tuple per order: (customer_id, order_id, date, items, amount)orders = [(c["customer_id"], o["order_id"], o["date"], o["items"], o["amount"]) for c in customers for o in c["orders"]]order_ids = [oid for _, oid, *_ in orders]signup_of = {c["customer_id"]: c["signup_date"] for c in customers}early = [oid for cid, oid, date, *_ in orders if date < signup_of[cid]] # ISO dates
# --- 2. Completeness: set algebra on the ids with gaps -------------------no_postal = {c["customer_id"] for c in customers if "postal_code" not in c["address"]}no_phone = {c["customer_id"] for c in customers if c.get("phone") is None}
# --- 3. Geography: is each city a store city of the customer's region? --wrong_city = [c["customer_id"] for c in customers if c["address"]["city"] not in STORE_CITIES[c["address"]["region"]]]all_store_cities = set().union(*STORE_CITIES.values())cities_used = {c["address"]["city"] for c in customers}
# --- 4. Orders over time: a dict of counts keyed by "YYYY-MM" ------------per_month = {}for _, _, date, _, _ in orders: per_month[date[:7]] = per_month.get(date[:7], 0) + 1per_year = {}for month, n in per_month.items(): per_year[month[:4]] = per_year.get(month[:4], 0) + npeak = max(per_month.values())peak_months = sorted(m for m, n in per_month.items() if n == peak)items_per_order = sum(items for *_, items, _ in orders) / len(orders)big_amount, big_cid, big_oid, big_date = max( (amount, cid, oid, date) for cid, oid, date, _, amount in orders)
# --- 5. Revenue by plan: a dict of dicts ---------------------------------plans = {}for c in customers: totals = plans.setdefault(c["plan"], {"customers": 0, "buyers": 0, "revenue": 0.0}) totals["customers"] += 1 totals["buyers"] += bool(c["orders"]) # True counts as 1 totals["revenue"] += sum(o["amount"] for o in c["orders"])
# --- 6. Pseudonymized export: a deep copy, so the source stays intact ----personal = {"name", "email", "phone"}shared = copy.deepcopy(customers)for record in shared: for field in personal & record.keys(): # only the fields this record has del record[field] record["address"] = {"region": record["address"]["region"]}source_intact = all({"name", "email"} <= c.keys() and "street" in c["address"] for c in customers)nothing_shared = all( s is not c and s["address"] is not c["address"] and s["tags"] is not c["tags"] and s["orders"] is not c["orders"] and all(a is not b for a, b in zip(s["orders"], c["orders"])) for s, c in zip(shared, customers))
# --- Report ---------------------------------------------------------------print(f"Customer audit: {len(customers)} records, exported {export['exported_at']}")print("=" * 58)print("Consistency")print(f" count field matches: {export['count'] == len(customers)}")print(f" unique customer ids: {len(set(ids)) == len(ids)} " f"unique emails: {len(set(emails)) == len(emails)}")print(f" unique order ids: {len(set(order_ids)) == len(order_ids)} " f"({len(order_ids)} orders) orders before signup: {len(early)}")print("Completeness")print(f" no postal code: {sorted(no_postal)}")print(f" no phone: {len(no_phone)} any gap: {len(no_postal | no_phone)} " f"both gaps: {sorted(no_postal & no_phone)}")print("Geography")print(f" city outside its region's store cities: {len(wrong_city)}")print(f" store cities without a customer: {sorted(all_store_cities - cities_used)}")print("Orders over time")print(f" per year: {dict(sorted(per_year.items()))} months with orders: " f"{len(per_month)}")print(f" busiest month(s): {', '.join(peak_months)} ({peak} orders)")print(f" items per order: {items_per_order:.2f}")print(f" largest: {big_oid} by {big_cid} on {big_date} ({big_amount:,.2f})")print("Revenue by plan")for plan in sorted(plans): t = plans[plan] print(f" {plan:<9} {t['customers']:>2} customers {t['buyers']:>2} buyers " f"{t['revenue']:>9,.2f} {t['revenue'] / t['customers']:>7,.2f} per customer")print("Pseudonymized export")print(f" fields: {', '.join(shared[0])}")print(f" address fields: {', '.join(shared[0]['address'])}")print(f" source intact: {source_intact} nothing shared: {nothing_shared}")
# --- Self-checks ------------------------------------------------------------assert len(set(order_ids)) == len(order_ids) == 48assert sum(per_year.values()) == len(orders)assert sum(t["customers"] for t in plans.values()) == len(customers)assert all(personal.isdisjoint(record) for record in shared)assert source_intact and nothing_sharedCustomer audit: 20 records, exported 2025-01-02T06:00:00Z==========================================================Consistency count field matches: True unique customer ids: True unique emails: True unique order ids: True (48 orders) orders before signup: 0Completeness no postal code: ['C00005', 'C00014'] no phone: 14 any gap: 14 both gaps: ['C00005', 'C00014']Geography city outside its region's store cities: 0 store cities without a customer: ['Boston', 'Detroit', 'Houston']Orders over time per year: {'2023': 34, '2024': 14} months with orders: 19 busiest month(s): 2023-05 (6 orders) items per order: 2.02 largest: O002016 by C00017 on 2023-05-22 (2,312.99)Revenue by plan basic 7 customers 7 buyers 5,629.30 804.19 per customer premium 6 customers 5 buyers 4,187.06 697.84 per customer standard 7 customers 5 buyers 3,895.34 556.48 per customerPseudonymized export fields: customer_id, signup_date, plan, address, tags, orders address fields: region source intact: True nothing shared: TrueRun it from the project folder:
python customer_audit.pyHow it works:
- Flat orders. The list of tuples turns the nested
orderslists into one row per order. Later steps unpack only the fields they need, with_and*_for the rest. - Consistency. A set drops duplicates, so a set shorter than its list means a repeated value. The lookup dict
signup_offinds the signup date of an order’s customer in one step, and ISO date strings compare in date order. - Completeness. Two sets of ids with gaps answer “any gap?” with
|and “both gaps?” with&. Here both customers without a postal code also have no phone. - Geography. A dict of sets gives an test per customer.
set().union(*sets)merges the four sets, and the difference with the cities in use shows the stores with no customer in this small export. - Orders over time. The month key
date[:7]is a slice of the ISO date. Rolling the months up into years needs no second pass over the orders. Putting the amount first in the tuples formax()makes it compare amounts. - Revenue by plan.
setdefault()creates the inner dict of a plan once.totalsis an alias of that inner dict, so+=updates the report.bool(c["orders"])adds 1 for a buyer and 0 otherwise. - Export.
copy.deepcopy()gives the export its own dicts and lists.personal & record.keys()is the set of personal fields that this record has, so the loop never deletes a missing key. Thenothing_sharedcheck tests every container, down to each order dict. The records keepcustomer_id, so the CRM team can link them back to a person: they are pseudonymized, not anonymous. - Self-checks. The asserts encode the facts that the report depends on. If someone changes the export logic and leaks a field, the fourth assert stops the script.
Alternative: build the export with a comprehension instead of a deep copy and del: {"customer_id": c["customer_id"], "plan": c["plan"], "address": {"region": c["address"]["region"]}, "tags": list(c["tags"]), ...}. It lists exactly the fields that leave the company, which is easier to review, but each nested list and dict must be copied by hand. The deep copy is shorter when you remove a few fields from many records.