2017-06-01 53 views
0

我有長度n的字典列表的列表。典型內容是:字典寫入到多個列(和行)

[{"description":"Lorem, ipsum, dolor, sit amet","error":"text_too_long"},{'description':'Sed ut perspiciatis, unde omnis','error':'text_too_long'},...] 

我想寫這一個CSV文件,其中「描述」和「錯誤」的形式兩列,行是列表中的每個元素。

我已經試過:

import csv, ast 
list_ = list_of_dictionaries #as a string 
with open('data.csv','wb') as f: 
    wtr = csv.writer(f) 
    for string in list_: 
     dictionary = ast.literal_eval(string) #converting to dictionary 
     to_write = [dictionary["description"],dictionary["error"]] 
     wtr.writerow([to_write]) 

這只是給了我整個字典中一列(但行是罰款)。我究竟做錯了什麼?

+0

你見過https://docs.python.org/2/library/csv.html#csv.DictWriter dictwriter類? –

回答

1

的字典可以直接設置,你不需要ast功能。

for dictionary in list_: 
    to_write = [dictionary["description"],dictionary["error"]] 
    wtr.writerow(to_write) # Not [to_write] 

會將字典寫入2列。

1

你能不能用pandas

data = [{"description":"Lorem, ipsum, dolor, sit amet","error":"text_too_long"},{'description':'Sed ut perspiciatis, unde omnis','error':'text_too_long'}] 

import pandas as pd 

df = pd.DataFrame(data) 

你得到這樣的:

df 
Out[246]: 
         description   error 
0 Lorem, ipsum, dolor, sit amet text_too_long 
1 Sed ut perspiciatis, unde omnis text_too_long 

然後用to_csv

df.to_csv('data.csv', index=False)