Codectionary / Developer documentation / Python

CSV Records with Headers

csv.DictReader maps header names to fields and handles quoted separators. Fields remain strings unless converted explicitly. Run as a Python 3.11+ script.

Syntax

csv.DictReader(file_object)

Examples

CSV Records with Headers

Run as a Python 3.11+ script.

import csv
import io
data = 'name,quantity\n"Tea, green",3\nCoffee,2\n'
rows = list(csv.DictReader(io.StringIO(data)))
print(rows[0]["name"])
print(sum(int(row["quantity"]) for row in rows))
  1. Expected output: Tea, green 5
  2. The comma inside the quoted name belongs to one field. Integer conversion is applied only to the numeric column.

Best practices

  • Open real CSV files with newline="" and an explicit encoding.
  • Validate expected headers and field values rather than splitting on commas.

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading