Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

csv.DictReader

Reads rows into dictionaries using header fields as names by default.

Version: Python 3.14; repository image, production runtime not attested

Syntax

csv.DictReader(f, fieldnames=None, restkey=None, restval=None, dialect='excel')

Reads rows into dictionaries using header fields as names by default.

Short rows are padded with the configured rest value; the header itself is consumed as metadata.

Iterate over records as dictionaries in field-name order. Omitting fieldnames consumes the first row as a header; passing names explicitly keeps the first row as data. A short nonblank row gets restval, while surplus cells go in a list under restkey. The defaults for both are None. The example supplies 'missing' for the absent score.

import csv
r = csv.DictReader(["a,b,c", "d"], fieldnames=["x", "y"], restkey="+", restval="-")
assert next(r) == {"x": "a", "y": "b", "+": ["c"]}
assert next(r) == {"x": "d", "y": "-"}

Examples

import csv
rows = csv.DictReader(["id,score", "7,9", "8"], restval="missing")
print(list(rows))

Result

[{'id': '7', 'score': '9'}, {'id': '8', 'score': 'missing'}]

Iterate over records as dictionaries in field-name order. Omitting fieldnames consumes the first row as a header; passing names explicitly keeps the first row as data. A short nonblank row gets restval, while surplus cells go in a list under restkey. The defaults for both are None. The example supplies 'missing' for the absent score.

Sources