How do you export prediction dictionaries in a fixed column order?
DictWriter follows fieldnames for column order and supplies a configured value for absent fields.
Python example and interpretation
Even when score is inserted first, the exported row begins with id. Unexpected keys raise by default, making them useful signals of schema drift.
import csv,io
f=io.StringIO()
w=csv.DictWriter(f,fieldnames=['id','score'],lineterminator='\n')
w.writeheader()
w.writerow({'score':7,'id':'r1'})
f.getvalue()Result 'id,score\nr1,7\n'
中文
如何让不同字典顺序的预测记录导出为同一列顺序?
DictWriter 用 fieldnames 指定输出顺序,并可为缺失字段写入预设值。
Python 算例与适用条件
输入先放 score 再放 id,CSV 仍以 id 开头。意料之外的键默认会报错,可据此发现导出契约发生变化。
import csv,io
f=io.StringIO()
w=csv.DictWriter(f,fieldnames=['id','score'],lineterminator='\n')
w.writeheader()
w.writerow({'score':7,'id':'r1'})
f.getvalue()结果 'id,score\nr1,7\n'