【发布时间】:2016-10-23 09:13:43
【问题描述】:
我有一个字典列表,其中包含随机键:值对。我还有一个列表 - 我想将字段写入 csv 文件的顺序(字典的基本键)。我使用下面的代码来编写 csv 文件。
lst=[{"b":2,"d":3},{"a":1,"b":1,"c":5},{"d":7,"c":1}...]
order = ["a","b","c","d"]
keys = lst[index].keys()
with open('file.csv', 'wb') as output_file:
dict_writer = csv.DictWriter(output_file, keys)
dict_writer.writeheader()
dict_writer.writerows(lst)
最终的 CSV 文件按顺序包含键:
b,d,a,c
2,3,,
但我要按照订单清单。我该怎么做?
【问题讨论】:
-
你为什么传递
lst[index].keys()而不是order? -
@BrenBarn:你想把它写下来作为答案吗?