2014-11-04 53 views
0

我想獲得下面的代碼來運行,但我不斷得到「字典包含字段不在字段名:'s','噸','d','e','v'。「字符串爆炸時使用Dict(zip(fieldnames,數據))函數和csv.DictWriter

def csv_dict_writer(loc, fieldNames, data): 

    with open(loc, "w", newline='') as out_file: 
     writer = csv.DictWriter(out_file, delimiter = ',', fieldnames=fieldNames, quoting=csv.QUOTE_ALL) 
     writer.writeheader() 
     print(loc,fieldNames,data) 
     for row in data: writer.writerow(row) 

setAndSpike = ['diff', 'min', 'max', 'mode', 'mean', 'stdev', 'var']; 
datSet = [2.88, 21.78, 24.67, 22.04, 23.06, 0.92, 0.85]; 
second = dict(zip(setAndSpike,datSet)); 
csv_dict_writer(filePath + 'textFirst.csv', setAndSpike, second) 

我已經進行了類似的話題進行搜索,並且他們都打開了不同的答案 - 使用CSV模塊報價,在DictWriter模塊不使用writerows,使我的鑰匙一個元組,襯裏數據集 - 但密鑰不斷出現,因爲爆炸的字符串。

奇怪的是,當我嘗試這個只與dict(zip(setAndSpike,datSet))它似乎很好地對齊。

我正在尋找任何幫助,甚至對這個主題的方向,如果它已被以前的答案。我找不到解決的類似問題,而且看起來很簡單。

我在Spyder2中通過Anaconda3和Python 3.4運行代碼。我可能會遇到一個新用戶,那是因爲我。

在此先感謝您的耐心和幫助。

回答

2
csv_dict_writer(filePath + 'textFirst.csv', setAndSpike, second) 

看起來csv_dict_writer的第三個參數應該是類型的字典列表,但你只有通過在一個單一的字典。嘗試將其包裝在一個列表中。

csv_dict_writer(filePath + 'textFirst.csv', setAndSpike, [second]) 
+0

釘住它。巨大的幫助,並感謝簡潔。 – double0darbo 2014-11-04 19:32:05