如何将类似键的python词典写入csv,其中键成为头字段。例如:
dict1 =
{
key1: value1,
key2: value2,
key3: value3,
}
dict2 =
{
key1: value4,
key2: value5,
key3: value6,
}
key1,key2,key3
value1,value2,value3
value4,value5,value6
答案 0 :(得分:2)
如果你还想要两个dicts,试试这个:
import csv
dict1 ={
"key1": "value1",
"key2": "value2",
"key3": "value3"}
dict2 ={
"key1": "value4",
"key2": "value5",
"key3": "value6"}
dict3 ={
"key1": "value7",
"key2": "value8",
"key3": "value9"}
data = [dict1,dict2,dict3]
dict_writer = csv.DictWriter(file('my.csv','wb'),fieldnames=dict1.keys())
dict_writer.writeheader()
dict_writer.writerows(data)
答案 1 :(得分:0)
你可以尝试这样:
#!/usr/bin/python
import csv
dict1 = {
'key1': 'value1',
'key2': 'value2',
'key3': 'value3',
}
with open('csv_test.csv', 'wb') as fh:
w = csv.DictWriter(fh, dict1.keys())
w.writeheader()
w.writerow(dict1)
答案 2 :(得分:0)
如果词典不同,请尝试以下操作:
import csv
dict1 = {1:'a',2:'b',3:'c'}
dict2 = {1:'aa',2:'bb',3:'cc'}
dict2[4] = 'dd'
keyset = set(dict1.keys() + dict2.keys())
with open('output.csv','w') as o:
f = csv.writer(o)
#write keys
keylist = list(keyset)
f.writerow(keylist)
rowlist = []
rowlist2 = []
for i in keylist:
if i in dict1.keys():
rowlist.append(dict1[i])
else:
rowlist.append('None')
if i in dict2.keys():
rowlist2.append(dict2[i])
else:
rowlist2.append('None')
f.writerow(rowlist)
f.writerow(rowlist2)