我有這樣詞典(鍵:[數組]):打印陣列以CSV
{'[email protected]': ['BMW', 'Dodge'],'[email protected]': ['Mercedes']}
和我想打印這對CSV和使一列的數組中的每個元素,所以結果應該像(標頭是可選的):
Owner,Car_1,Car_2
[email protected], BMW, Dodge
[email protected], Mercedes
謝謝!
我有這樣詞典(鍵:[數組]):打印陣列以CSV
{'[email protected]': ['BMW', 'Dodge'],'[email protected]': ['Mercedes']}
和我想打印這對CSV和使一列的數組中的每個元素,所以結果應該像(標頭是可選的):
Owner,Car_1,Car_2
[email protected], BMW, Dodge
[email protected], Mercedes
謝謝!
使用python csv
模塊。
import csv
d = {'[email protected]': ['BMW', 'Dodge'],'[email protected]': ['Mercedes']}
with open('Cars.csv', 'w', newline='') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=',')
spamwriter.writerow(['Owner', 'Car_1', 'Car_2'])
for k, v in d.items():
spamwriter.writerow([k] + v)
您可以使用csv.writer
,假設你的數據存儲在字典d
import csv
with open('output.csv', 'w') as fp:
writer = csv.writer(fp)
writer.writerow(['Owner','Car_1','Car_2'])
for key, val in d.items():
writer.writerow([key] + val)
非常感謝! :) – skutik
可能的答案https://stackoverflow.com/questions/3086973/how-do-i -convert-this-list-of-dictionaries-to-a-csv-file-python –
同時檢查https://stackoverflow.com/questions/8331469/python-dictionary-to-csv –