Check Missing Fields Before Exporting Warehouse Rows with DictWriter
A CSV export can lose the distinction between a missing dictionary field and an intentionally empty field. DictWriter can fill a missing field with its restval, which defaults to an empty string. Reject a missing required key before writing if the export contract requires every field.
The example concerns global dropshipping records and warehousing and fulfillment data exchange. It uses synthetic rows and a memory buffer, with no customer details or production connection.
import csv
import io
FIELDS = ['sku', 'qty']
def export_row(row):
if set(row) != set(FIELDS):
raise ValueError('row keys do not match the export fields')
stream = io.StringIO(newline='')
writer = csv.DictWriter(stream, fieldnames=FIELDS, extrasaction='raise')
writer.writeheader()
writer.writerow(row)
return stream.getvalue()
def read_export(text):
return list(csv.DictReader(io.StringIO(text, newline='')))
assert read_export(export_row({'sku': 'A', 'qty': 0})) == [
{'sku': 'A', 'qty': '0'}
]
assert read_export(export_row({'sku': 'A,B', 'qty': 2}))[0]['sku'] == 'A,B'
assert read_export(export_row({'sku': 'line\nbreak', 'qty': 2}))[0]['sku'] == 'line\nbreak'
assert read_export(export_row({'qty': 2, 'sku': 'A'}))[0]['qty'] == '2'
for invalid in [{'sku': 'A'}, {'sku': 'A', 'qty': 2, 'extra': 'x'}]:
try:
export_row(invalid)
except ValueError:
pass
else:
raise AssertionError('invalid field set accepted')
assert read_export(export_row({'sku': 'A', 'qty': ''}))[0]['qty'] == ''
assert read_export(export_row({'sku': 'A', 'qty': None}))[0]['qty'] == ''
print('8 checks passed')
The DictWriter documentation describes fieldnames, restval and extrasaction. The executed cases cover zero, a quoted comma, an embedded newline, dictionary insertion order, missing and extra keys, and the empty output produced for an empty string or None.
The last two cases are a deliberate limitation: checking key presence does not validate the value. If empty quantities or None are forbidden, add a value rule before serialization. CSV itself will not preserve a meaningful distinction between these two values under this writer's behavior.
The small helper rejects extra keys even though the writer also guards them, so missing and extra fields have the same boundary error. It is not a full inventory schema or a spreadsheet safety policy. Decide the field and value contract with the consumer before adding this to an exporter.

Computer workstations and printing equipment in a warehouse.
All rights reserved