Python Glossary Русский

all Python 3Files & I/Oterm

csv.DictReader

csv — reading

A CSV reader that yields each record as a dict: the keys come from the first (header) row or from the fieldnames parameter.

Syntax

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

If a row has fewer fields than the header, the missing keys get None (or restval), and extra values are collected in a list under the key None (or restkey) — corrupted data is easy to miss. If you pass fieldnames, the first line of the file becomes data, not a header. Values are always strings, as with reader; since 3.8 rows are plain dicts, not OrderedDict.

Examples

import csv
import io
buf = io.StringIO('name,age\nAnna,30\nBob\nCid,1,extra\n')
for row in csv.DictReader(buf):
    print(row)
# → {'name': 'Anna', 'age': '30'} / {'name': 'Bob', 'age': None} / {'name': 'Cid', 'age': '1', None: ['extra']}

See also

Open in the full glossarydocs.python.orgReport an inaccuracy