CKTIS / Python
csv.DictWriter
Writes mapping values in the explicit field order supplied to the writer.
Version: Python 3.14; repository image, production runtime not attested
Syntax
csv.DictWriter(f, fieldnames, restval='', extrasaction='raise', dialect='excel')Writes mapping values in the explicit field order supplied to the writer.
A missing key uses the configured rest value. Extra keys normally cause a ValueError.
Supply a writable text stream and mandatory fieldnames to choose the output column order. writeheader writes those names, and writerow looks up the corresponding keys. Missing keys use restval, by default an empty string. Unknown keys raise ValueError unless extrasaction='ignore'. The sample prints id,score followed by 7,-.
import csv, io
out = io.StringIO(newline="")
w = csv.DictWriter(out, ["a"], lineterminator="\n", extrasaction="ignore")
w.writeheader()
w.writerow({"b": 2})
assert out.getvalue() == 'a\n""\n'
try:
csv.DictWriter(out, ["a"]).writerow({"b": 2})
except ValueError:
pass
else:
raise AssertionError
Examples
import csv
from io import StringIO
out = StringIO(newline="")
w = csv.DictWriter(out, ["id", "score"], restval="-", lineterminator="\n")
w.writeheader()
w.writerow({"id": 7})
print(out.getvalue(), end="")
Result
id,score 7,-
Supply a writable text stream and mandatory fieldnames to choose the output column order. writeheader writes those names, and writerow looks up the corresponding keys. Missing keys use restval, by default an empty string. Unknown keys raise ValueError unless extrasaction='ignore'. The sample prints id,score followed by 7,-.