CSV and Text
CSV to Dicts
Convert parsed CSV rows into a list of dicts by zipping the header row with
each data row. The replay shows rec being built fresh for each row via
dict(zip(header, fields)) before being appended to records.
By hand
The Pythonic way
csv.DictReader reads the header automatically and yields one dict per data
row. list(...) materialises the result.
naive.py
csv_text = 'id,cat,val\n1,x,10\n2,y,20\n3,x,30'
lines = csv_text.split('\n')
header = lines[0].split(',')
records = []
# trace: ignore records
for line in lines[1:]:
rec = dict(zip(header, line.split(',')))
records.append(rec)
print('RESULT:', records[-1])
library.py
import csv
import io
csv_text = 'id,cat,val\n1,x,10\n2,y,20\n3,x,30'
records = list(csv.DictReader(io.StringIO(csv_text)))
print('RESULT:', records[-1])
RESULT: {'id': '3', 'cat': 'x', 'val': '30'}
Implementation notes
- RESULT prints the last dict; the full list of 3 dicts would exceed the 80-char repr limit.
dict(zip(header, fields))is the building block behindcsv.DictReader— both pair column names with values positionally.- All field values are strings after CSV parsing; use
int(rec['val'])or similar to convert numeric columns. - See
parse-csv-rows(this chapter) for the prior step that produces the raw row lists this lesson consumes.