将带有多个值的字典写入CSV可以通过以下步骤实现:
import csv
data = {
'key1': ['value1', 'value2', 'value3'],
'key2': ['value4', 'value5', 'value6'],
'key3': ['value7', 'value8', 'value9']
}
csv_file = 'data.csv'
with open(csv_file, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(data.keys())
writer.writerows(zip(*data.values()))
file.close()
完整的代码示例:
import csv
data = {
'key1': ['value1', 'value2', 'value3'],
'key2': ['value4', 'value5', 'value6'],
'key3': ['value7', 'value8', 'value9']
}
csv_file = 'data.csv'
with open(csv_file, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(data.keys())
writer.writerows(zip(*data.values()))
file.close()
这样,带有多个值的字典就会被写入到名为"data.csv"的CSV文件中。
领取专属 10元无门槛券
手把手带您无忧上云