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)Report a problem with this exampleOpens a pre-filled issue on GitHub.