From CSV file to records you can query
A test rig writes a CSV with a header row and 2,000 lines. How do you ask 'which runs drew more than 1.5 A?' without counting columns by hand?
About 40 min · 3 goals · Checked by automated tests
1.Why should I care?
Most engineering data arrives as text tables: test-rig logs, inventories, sensor exports. Turning each row into a dictionary keyed by column name makes every later question readable and robust to someone adding a column.
- ◇ Load a CSV file into a list of dictionaries with csv.DictReader.
- ◇ Convert text fields to numbers safely and handle missing or bad values.
- ◇ Group and summarise records with dictionaries.
2.Watch
→ Watch how DictReader uses the header row as keys, and how the writer produces a CSV from dictionaries.
Reads and writes real CSV files with csv.reader and csv.DictReader, the same tools you use on a sensor log.
Length: see YouTube · captions on YouTube · source
Nothing loads from YouTube until you press play.
The video is optional: everything you need is also in the lesson text and the interactive.
3.Predict
csv.DictReader reads the row 'run,current_a' / '3,1.72'. What is type(row['current_a'])?
Guess first. Being wrong here is how the surprise works.
4.Discover
In the Code Lab, paste the worked example. Run it, then add a row with an empty current and one with 'n/a'. Make the loader skip bad rows but count them, and print how many were skipped.
Can't use the interactive? Read a description instead
The Code Lab activity can be done on paper: from the five-row log, motor A has currents 1.20 and 1.31 (mean 1.255 A) and motor B has 1.72 and 1.66 (mean 1.69 A); run 4 has an empty current and is skipped and counted.
5.Checkpoint: guided practice
Check what you just discovered before going on. Hints appear after a wrong answer.
Practice 1
row = {'run': '4', 'current_a': '1.5'} from DictReader. What does row['run'] + 1 do?
Practice 2
In the worked example, if the empty current for run 4 is fixed to 1.75, what is motor B's average current (3 decimal places)?
6.Understand
Rows as dictionaries
csv.DictReader uses the header row as keys, so each row becomes {"run": "3", "motor": "B", "current_a": "1.72"}. Code that says row["current_a"] keeps working if someone inserts a new column; code that says row[2] silently reads the wrong one.
Text in, numbers out, carefully
Every field is a string. Convert with int() or float() inside a try block, and decide a policy for bad values: skip and count them, or stop with an error naming the line. Never let a bad row quietly become 0.
Group with a dictionary
To summarise by category, build a dict of lists: by_motor.setdefault(row["motor"], []).append(current). Then each key's list can be averaged or counted. Dictionaries are the natural shape for 'one answer per name'.
Explain it another way
A CSV is a spreadsheet saved as plain text. DictReader is like reading each row while keeping your finger on the header, so you always know which number is which.
csv handles quoting and commas inside fields, which a naive line.split(",") gets wrong. io.StringIO lets you test a loader on a string instead of a real file. Opening files with newline="" is the documented way to let the csv module handle line endings.
Test engineers often keep raw rig logs untouched and write loaders that report how many rows were rejected and why, so the cleaning step is visible in the final report.
Worked example 1
Load a motor test log, skip bad rows, and average current per motor.
import csv
import io
LOG = """run,motor,current_a
1,A,1.20
2,B,1.72
3,A,1.31
4,B,
5,B,1.66
"""
def load_runs(text):
"""Return (records, skipped). Each record has run (int), motor (str), current_a (float)."""
records, skipped = [], 0
for row in csv.DictReader(io.StringIO(text)):
try:
records.append({"run": int(row["run"]), "motor": row["motor"], "current_a": float(row["current_a"])})
except ValueError:
skipped += 1
return records, skipped
runs, bad = load_runs(LOG)
by_motor = {}
for r in runs:
by_motor.setdefault(r["motor"], []).append(r["current_a"])
for motor, values in sorted(by_motor.items()):
print(motor, round(sum(values) / len(values), 3), len(values))
print("skipped", bad)
# A 1.255 2
# B 1.69 2
# skipped 1Common mix-ups
- line.split(',') is all you need to read a CSV.
✓ Quoted fields can contain commas. The csv module handles quoting correctly. - A missing value can be treated as zero.
✓ Zero is a measurement. Missing is the absence of one, and must be handled and reported separately.
7.Practice on your own
Practice, not a test. Wrong answers get a hint and another try.
Practice 3
Some rows have current 'n/a'. Which policy is best for an engineering report?
Practice 4
Which line adds current to a per-motor list, creating the list the first time a motor appears?
Practice 5 · a fresh version every time
A log of motor temperature (°C) reads xs = [42, 50, 49, 47, 47, 44, 43, 44, 47]. What is the mean, statistics.mean(xs)? Give 2 decimal places.
8.Apply it
Write a loader for a part inventory CSV (part_no, description, qty, mass_g) that returns a list of dicts and a count of rejected rows. Use it to answer: which parts have qty below 10, and what is the total mass in stock in kg? Test the loader on a string containing at least one bad row.
9.Reflect
10.Go further
- Python docs: csv ↗DictReader, DictWriter, dialects and quoting rules.
Concepts: Lists, dictionaries and tabular data · Testing and debugging