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.

PythonData Integrity

Code

pythonsnippet
19 lines
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

  • csv must 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

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.