Results.

SCEPTRA.TECH

Python DictReader Lost a CSV Column? Check for Duplicate Headers First

Original diagram showing duplicate amount headers reducing three CSV columns to two dictionary keys

A CSV export contains three columns, but the imported dictionary has only two keys. Before blaming quoting or encoding, inspect the header row. With Python's csv.DictReader, two columns using the same name cannot remain separate dictionary keys. A later value can replace an earlier one without a parsing error.

I check header uniqueness before reading business records. That keeps a structurally valid CSV from quietly becoming an incomplete report. The important distinction is between parsing CSV syntax and validating the schema your application expects.

Reproduce the loss with one small record

Run this example in Python:

import csv
from io import StringIO

text = chr(10).join(["item,amount,amount", "pen,12,8", ""])
reader = csv.DictReader(StringIO(text), strict=True)
print(reader.fieldnames)
print(next(reader))

The headers print as ['item', 'amount', 'amount'], but the record prints as {'item': 'pen', 'amount': '8'}. The value 12 no longer has its own field in that dictionary. This is not a failed numeric conversion: DictReader returns these values as strings.

Notice that strict=True did not reject the repeated name. That option concerns bad CSV input under the parser's dialect. It is not a promise that column names are unique or that the file matches your reporting contract.

Validate the names before consuming records

Here is a small guard for exact duplicate names and blank names. Continue in the same session so the imports remain available:

def checked_reader(stream):
    reader = csv.DictReader(stream, strict=True)
    names = reader.fieldnames
    if not names:
        raise ValueError("Missing header row")
    seen = set()
    for column, name in enumerate(names, start=1):
        if not name.strip():
            raise ValueError(f"Blank header at column {column}")
        if name in seen:
            raise ValueError(f"Repeated header at column {column}: {name!r}")
        seen.add(name)
    return reader

fixed = chr(10).join(["item,ordered_amount,received_amount", "pen,12,8", ""])
rows = list(checked_reader(StringIO(fixed)))
print(rows)
assert rows[0]["ordered_amount"] == "12"
assert rows[0]["received_amount"] == "8"

Accessing reader.fieldnames reads the header when none was supplied explicitly. The returned reader is then positioned for data records. Calling checked_reader(StringIO(text)) on the original broken example raises a ValueError identifying column 3, before any data row becomes a dictionary.

The corrected sample uses two deliberately different names because ordered and received amounts have different meanings. The result keeps both strings, 12 and 8. Only make that change when you know what each source column represents. Renaming columns by guesswork can preserve bytes while corrupting meaning.

Choose an explicit rule for near-matches

This guard compares names exactly. It rejects a whitespace-only header, but it does not strip valid names or merge Amount with amount. If your downstream system trims spaces or ignores case, validate uniqueness again under that same normalization rule before mapping records.

Do not silently normalize first and hope for the best. Two distinct source names can collapse into one destination name. Keep the original names and column positions available for diagnosis, and agree on a mapping with whoever produces the export.

If repeated headers are intentional, use csv.reader to retain positional lists until you have an explicit schema. Avoid line.split(','): a quoted field may contain a comma, so that shortcut is not a CSV parser.

Unique headers are only one gate

A file can pass this check and still contain too many or too few values in a record. DictReader stores excess values under its restkey and supplies restval for missing fields. Validate row width separately if every record must match the header. Required names, value types and allowed ranges also need their own checks.

For an actual file, open the agreed encoding with newline="" and pass that file object into the guard. Do not add an encoding-error suppression rule just to get the import through. Diagnose the source format instead.

What I checked

I executed both displayed blocks with Python 3.10.12 using synthetic CSV strings. Separate checks covered duplicate headers, a whitespace-only name, empty input, a header-only file, distinct case-sensitive names and a quoted header containing a comma. This is a local behavior test, not a production import audit or a test of every CSV dialect.

Sources: Python CSV reference and the CPython discussion of duplicate DictReader headers.

Comments