Python csv.DictReader
csv.DictReader takes its field names from the first row by default and returns the remaining rows as dictionaries of strings.
A simple example
csv.DictReader
- Start with CSV row containing A,2
- Do this Parse the two fields
- Result A and 2
Syntax
for row in csv.DictReader(stream)
Run this example in Python
Save the program as lesson.py. Use Python 3.9 or later.
python3 lesson.py
Read quoted fields by column name
A supplier sends a CSV invoice whose quoted description contains a comma. Use a CSV reader that understands quoting so the amount stays in its proper column and the description remains intact.
import csv
from io import StringIO
data = 'item,qty\n"bolts, steel",3\nnuts,1\n'
for row in csv.DictReader(StringIO(data, newline="")):
print(row["item"], int(row["qty"]) * 2)
bolts, steel 6 nuts 2
A quoted comma stays inside the item name. Convert the quantity explicitly before arithmetic. When opening a CSV file on disk, pass newline="" to open.
Python documentation for csv.DictReader
Read an exhibit order
A curator enters a material and finish together inside a quoted item name. Read the quoted field as one CSV cell. What item name belongs to this row?
Read a studio purchase
A technician enters a cable description with a comma inside the field. Read the quoted field as one CSV cell. What item name belongs to this row?