3 回答
TA贡献1846条经验 获得超7个赞
首先,您必须确保字典值中的所有列表都具有相同的长度。任何其他情况都是不好的做法。
假设是这种情况,例如
d = {'ID':[1,2,3,4,5,6,7],
'Name':['A','B','C','D','E','F','G'],
'Flag':[True, False, False, False, False, False, False],
'City':['']*7,
}
现在您可以构建一个数据框
import pandas as pd
df = pd.DataFrame.from_dict(d)
并将其转换为 CSV
df.to_csv('/tmp/test.csv', index=False)
TA贡献1770条经验 获得超3个赞
如果您不是像您提到的那样严格寻找 csv,并且可以在其中包含NaNs,请尝试使用pandas.
import pandas as pd
d = {
"ID": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
"Name": ["A", "B", "C", "D", "E", "F", "G"],
"Flag": ["True"],
"City": "",
}
df = pd.DataFrame(dict([(k, pd.Series(v)) for k, v in d.items()]))
df.to_csv("1.csv",index=False)
这会用 填充不可用的元素NaN。
输出:
ID Name Flag City
0 1 A True
1 2 B NaN NaN
2 3 C NaN NaN
3 4 D NaN NaN
4 5 E NaN NaN
5 6 F NaN NaN
6 7 G NaN NaN
7 8 NaN NaN NaN
8 9 NaN NaN NaN
9 10 NaN NaN NaN
TA贡献1876条经验 获得超7个赞
import csv
columns = list(dict.keys())
try:
with open(output_file, 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=columns)
writer.writeheader()
for data in dict:
writer.writerow(data)
except IOError:
print("I/O error")
添加回答
举报