Library contents

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

  1. Start with CSV row containing A,2
  2. Do this Parse the two fields
  3. Result A and 2
The comma marks the field boundary. A header can supply names for those fields.

Syntax

Python 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.

From the programdata = 'item,qty\n"bolts, steel",3\nnuts,1\n'
First output linebolts, steel 6
lesson.py
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)
Output
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

Advertisements

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?

Given"clay, red",7
Worked resultclay, red

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?

Given"lead, stereo",2
Worked resultlead, stereo