Recent chats
ASKGEEZ Q&A GUIDETechnology & devices

How can I read CSV rows by column name using DictReader?

Quick answer

Use csv.DictReader to turn each data row into a dictionary keyed by the header names. Check reader.fieldnames against the headers your program requires before processing rows. Report unexpected headers, and explicitly check each row for extra values or missing fields: DictReader puts extras under None by default and fills missing fields with None unless you set restkey or restval. Header checks alone do not validate row contents. [S1]

LET’S WORK THROUGH IT

The question, the details, the next step.

Question

I have a CSV with a header row. How do I get a value by its column name instead of remembering its position?

Geez

Use csv.DictReader: by default, it uses the first row as field names and gives you each following row as a dictionary keyed by those names. [S1] For example, if a header is name,department, a row can be accessed as row["department"].

The example below assumes the file is named people.csv, has a header row, and that name and department are required headers. It reports other headers, stops if a required header is absent, and flags rows with missing or extra fields. Adjust the assumed names and filename to match your file.

import csv

expected = {"name", "department"}
missing_value = object()

with open("people.csv", newline="", encoding="utf-8") as file:
    reader = csv.DictReader(
        file,
        restkey="__extra_fields__",
        restval=missing_value,
    )
    headers = reader.fieldnames or []
    header_set = set(headers)

    missing_headers = expected - header_set
    unexpected_headers = header_set - expected

    if missing_headers:
        print("Missing required headers:", sorted(missing_headers))
    if unexpected_headers:
        print("Unexpected headers:", sorted(unexpected_headers))

    if missing_headers:
        raise SystemExit("Cannot process rows without required headers")

    for row_number, row in enumerate(reader, start=2):
        extras = row.get("__extra_fields__")
        missing_fields = [
            name for name in expected
            if row.get(name, missing_value) is missing_value
        ]

        if extras or missing_fields:
            print(
                f"Row {row_number}: extra values={extras}, "
                f"missing fields={sorted(missing_fields)}"
            )
            continue

        print(row["name"], row["department"])

Here, restkey gives extra row values a named place, and restval marks missing values with a distinct sentinel. The standard defaults instead place extra values under None and fill missing values with None. [S1]

Follow-up question

Why check the headers separately if DictReader already creates dictionaries?

Geez

A dictionary can be created even when the CSV header does not match what your code expects. Checking reader.fieldnames lets you detect absent required columns before trying to read them. The documentation describes inspecting field names and comparing them with required names; the caller decides what to do when a required header is absent. [S1]

In the example, a missing required header is reported and processing stops. Unexpected headers are reported, but the program can continue because the chosen policy only requires name and department. That is a policy choice, not proof that the data is valid. DictReader's mapping does not validate that rows fit your intended schema. [S1]

Follow-up question

What happens if one row has too many or too few values? Is the header check enough?

Geez

No. A header check compares column names, not the number of values in every data row. By default, extra row values are collected under the key None, while missing values are filled with None; restkey and restval let you choose different markers. [S1]

The example uses a named key for extras and a unique sentinel for missing values, then prints a row-specific report and skips that row. You could instead collect the row for review or stop processing. Choose one policy deliberately. The documentation does not establish that a row's values are meaningful or correctly typed; those checks depend on your application and data.

Follow-up question

Can you show what the report might look like, and what should I check before using this pattern?

Geez

Assume the required headers are name and department, and a particular row is short one field. The output would be similar to:

Row 3: extra values=None, missing fields=['department']

If a row has values beyond its headers, the report includes those values in extra values. The number in the sample is a record number: it starts at 2 because the first record is the header. DictReader's parsing also depends on the selected CSV dialect, so adapt the sample if the file uses a different delimiter or quoting convention. [S1]

Before relying on the results, decide whether unexpected headers are allowed, whether irregular rows should be skipped or stop the task, and what validation your application needs after parsing.

A practical checklist

  • Set the required column names to match the CSV headers you expect.

  • Inspect reader.fieldnames and report missing required headers before processing rows.

  • Choose whether unexpected headers are warnings or reasons to stop.

  • Set restkey and restval if you need to identify extra or missing row fields explicitly.

  • Choose how to handle irregular rows, and validate values separately if your application requires it.

A few more useful answers

Does DictReader check that every row matches my intended schema?

No. It maps row values to headers, but that mapping does not validate the intended schema. Check headers and irregular row lengths explicitly, then add any application-specific validation you need. [S1]

How can I report extra values in a row?

Set restkey to a key such as "__extra_fields__", then check that key on each row. By default, DictReader stores extra values under None. [S1]

What does DictReader use if a row has fewer values than the header?

By default, missing fields are filled with None. You can set restval to a distinct marker and check for it explicitly. [S1]

Sources

References used for this guide.

  1. [S1] csv — CSV File Reading and Writing (Python 3.14 documentation)
    docs.python.org · Checked

YOUR QUESTION. YOUR DETAILS.

Let’s work through your situation.

Get a tailored answer or help with your next task. Starts at $1, with a quote before you pay.

Ask your own question
← Back to Geez at Work