【发布时间】:2016-01-28 20:49:09
【问题描述】:
我正在尝试通过将键与 csv 标题中的列相匹配,将多个字典(键和值)推送到 csv 文件。 示例:
import csv
d1 = {'a':1, 'b':2, 'c': 3}
d2 = {'d':4, 'e':5, 'f': 6}
with open('my_data.csv','wb') as f:
w = csv.writer(f)
w.writerow(['a', 'b', 'c', 'd', 'e', 'f'])
#iterate through all keys in d1,d2,dn
#if key matches column:
#write value of key to the bottom of column
#else:
#error key not found in header
mydata.csv 中的预期结果
a,b,c,d,e,f
1,2,3,4,5,6
【问题讨论】:
-
不确定我明白了。您是否将所有 dicts 合并到输出文件中的一行中(如图所示)?还是您希望每个输入字典成为输出文件中的一行?
标签: python parsing csv dictionary