![](/img/trans.png)
[英]Writing a python Dictionary to a CSV file with keys as column headers
[英]Python dictionary keys to csv file with column match
我正在尝试通过将键匹配到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
答案是..不仅将列名传递给writerow()..将它们放在变量columns
,然后使用它来控制值的写出顺序。 Python字典没有顺序。您必须使用一些代码才能将值排序为所需的顺序。
代码的最后一行将这些值写到CSV中,使用了一个名为List Comprehension的python功能。 这是保存3-4行代码的快捷方式。 查一下,它们非常方便。
import csv
d1 = {'a':1, 'b':2, 'c': 3}
d2 = {'d':4, 'e':5, 'f': 6}
columns = ['a', 'b', 'c', 'd', 'e', 'f']
# combine d1 and d2 into data.. there are other ways but this is easy to understand
data = dict(d1)
data.update(d2)
with open('my_data.csv','wb') as f:
w = csv.writer(f)
w.writerow(columns)
# make a list of values in the order of columns and write them
w.writerow([data.get(col, None) for col in columns])
如果没有列表理解,这会是什么样子:
row = []
for col in columns:
row.append(data.get(col, None))
w.writerow(row)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.