Write CSV Rows From Dictionaries
Write dictionaries to CSV with a declared header order, ensuring every row has the same columns even when fields are missing.
Code
import csv
import io
from typing import Dict, Iterable, List
def to_csv(rows: Iterable[Dict[str, object]], columns: List[str]) -> str:
buffer = io.StringIO()
writer = csv.DictWriter(buffer, fieldnames=columns, extrasaction="ignore")
writer.writeheader()
for row in rows:
writer.writerow({column: row.get(column, "") for column in columns})
return buffer.getvalue()
output = to_csv(
[{"id": 1, "name": "ada"}, {"id": 2}],
["id", "name", "email"],
)
print(output)Output
Captured from a sandboxed run of this snippet in the build pipeline.
id,name,email
1,ada,
2,,Inside the snippet
Write CSV Rows From Dictionaries keeps everything in the function to_csv.
Iteration happens inside for row in rows — everything outside it runs once. The snippet’s external surface is Dict, Iterable, List, all of it via csv.
What to watch for
csvmust be installed first — the snippet imports it directly.
Putting the pieces to work
The primary signature is def to_csv(rows: Iterable[Dict[str, object]], columns: List[str]) -> str
to_csv is the public entry point; everything else in the file exists to support it.
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
- Is a package install part of the setup?
- No. Installation is unnecessary because only built-in APIs are used. Every import resolves inside the standard library — `csv`, `io`, `typing`. The file defines `to_csv` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.