csv.DictReader restkey and restval Guard Ragged Rows

Handle CSV rows with extra or missing trailing columns cleanly using csv.DictReader restkey and restval before normalizing via DictWriter.

PythonData Integrity

Code

snippet
import csv
import io

raw_csv = (
    "id,role,region\n"
    "u-1,admin,us-east,audit-override,extra-note\n"
    "u-2,viewer\n"
    "u-3,editor,eu-west\n"
)

# restkey captures overflowing trailing cells; restval fills missing trailing cells
reader = csv.DictReader(io.StringIO(raw_csv), restkey="_extra", restval="unassigned")
rows = list(reader)
for row in rows:
    print(row["id"], "role=", row["role"], "region=", row["region"], "extra=", row.get("_extra", []))

# DictWriter with extrasaction="ignore" drops _extra cleanly on export
out = io.StringIO()
writer = csv.DictWriter(out, fieldnames=["id", "role", "region"], extrasaction="ignore", lineterminator="\n")
writer.writeheader()
writer.writerows(rows)
print("normalized:\n" + out.getvalue().strip())

Output

Captured from a sandboxed run of this snippet in the build pipeline.

normalized:id,role,region

Walkthrough notes — csv.DictReader restkey and restval Guard Ragged Rows

The cycling part of this snippet is for row in rows.

The execution flow below consumes top-level variables declared here: raw_csv, reader, rows, out.

Caveats

  • No package installation, no environment variables, no setup steps.

Putting it to use

The file’s steps show up in the output as normalized:\n.

Core lines

for row in rows:
    print(row["id"], "role=", row["role"], "region=", row["region"], "extra=", row.get("_extra", []))

Interactive Tools for This Topic

FAQ

Are there dependencies to manage?
No. There are no dependencies to declare or install. Every import resolves inside the standard library — `csv`, `io`. Its state lives in module-level bindings: `raw_csv`, `reader`, `rows`.