我有一個字典列表,其中包含隨機鍵:值對。我也有一個列表 - 我想將字段寫入csv文件的順序(Essentialy字典的鍵)。我使用下面的代碼來編寫csv文件。將python中的字典列表寫入具有特定字段順序的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
@BrenBarn:你想把它作爲答案嗎? – SuperSaiyan