liveBook · Manning

DictReader

As explained in Python How-To

DictReader is a csv-module reader that maps each CSV row's fields to keys taken from the header row.

Use csv.DictReader when a CSV file has a header row and each record should be accessed as a dictionary. It takes the first row as keys, avoiding the manual combination of next, zip, and dict. section 11.2.2 section 11.6

Read task records as dictionaries

with open("tasks.txt", newline="") as file: csv_reader = csv.DictReader(file) for row in csv_reader: print(row) # {'task_id': '1001', 'title': 'Homework', 'urgency': '5'} # {'task_id': '1002', 'title': 'Laundry', 'urgency': '3'} # {'task_id': '1003', 'title': 'Grocery', 'urgency': '4'} Each iteration produces a dictionary whose keys come from the header: task_id, title, and urgency. The values remain strings in the displayed output. section 11.2.2

task_id,title,urgency
1001,Homework,5
1002,Laundry,3
1003,Grocery,4

Use this sample CSV to see how the header fields become dictionary keys for each task row. section 11.2.2

Prefer this pattern when:

  • The CSV includes a header and the field names should remain attached to their values. section 11.2.2
  • The file should close automatically after reading; open it with a with statement. section 11.6
  • All records are needed at once; convert the iterator with list(csv_reader). section 11.2.2

How Python How-To covers it

How deep it goes
Demonstrates construction, iteration, output, and the iterator-to-list question without exploring advanced configuration.
Examples
Uses a task CSV containing task_id, title, urgency, and three task records.
What it assumes
Assumes basic file handling, with statements, iteration, and CSV structure; demonstrates header handling from the basic case.
What you can do after
Apply it via Python's csv module to read header-based records as dictionaries.
How it connects
Contrasts with csv.reader and aligns with csv.DictWriter for header-aware CSV processing.

Also explained in

Compare how 2 books explain DictReader →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.