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.
Code
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,regionWalkthrough 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
CSV Column AnalyzerProfile every CSV column with inferred types, empty-cell counts, unique values, and numeric min and max ranges.CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.CSV to Markdown TableConvert CSV data, including quoted fields with embedded commas and newlines, into a clean GitHub-flavored Markdown table with selectable alignment.CSV to TSV ConverterParse RFC 4180 CSV with quoted fields and re-serialize using a tab, pipe, semicolon, or custom delimiter, with optional quoting.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.