2015-06-19 32 views
-1

我已經生成了一個dict字典,每個字典包含5個隨機生成的字符串元素。如何使用每行多個值的DictWriter將str值轉換爲csv

我想輸出每個字典到一個CSV文件中的單行,只有「乾淨」的字符串值,沒有引號或括號。

開始與此:

numberofhands = range(int(raw_input("# of hands you want to generate: "))) 

allhands = {} #create a place for all the hand dicts to go 

for i in numberofhands: # loads allhands with specified # of 5 card hands 
temphand = makehand(battlepile) 
allhands.update({i:temphand}) 

with open(nameoffile,'wb') as outfile: #makes csv using writer and list of dict values 
writer = csv.writer(outfile,delimiter='\t') 
for key, value in allhands.items(): 
    aRow = [] 
    for i in value: 
     aRow.append(value[i]) 
    writer.writerow([aRow]) 

輸出看起來是這樣的:

['蜘蛛'飛船'邪惡'豪豬 '亮劍']

[」 Train''Sumo Wrestler''Saw''Glass''Robot']

['Bees''Cannon''House''TNT''Sumo Wrestler']

['空氣'蜘蛛'風'飛船 '辣']

['海龜 '聖誕老人' '車''飛機 '雲']

我的目標是讓輸出看起來像這樣:

蜘蛛飛船危機豪豬劍

列車相撲看見玻璃機器人

只蜜蜂農府T.N.T相撲

空氣蜘蛛風飛船辣

龜聖誕老人汽車飛機雲

我與DictWriter掙扎 - 是有一個更清潔,Python的方式來實現這一目標?這裏就是我目前:

with open(nameoffile, 'wb') as outfile: #makes csv using DictWriter and list of dict values 
fieldnames = [1,2,3,4,5] 
writer = csv.DictWriter(outfile, dialect='excel', fieldnames=fieldnames) 
for key, value in allhands.items(): 
    writer.writeheader() 
    for k, v in value[key]: 
     writer.writerow([v]) 

其中給出KeyError: 0

我明白任何指導。

回答

0

這裏有一個例子,說明如何通過DictWriter從字典寫入CSV文件。

我箍它幫助。

import csv 
allhands = {1:'Spider', 2:'Spaceship', 3:'Evil', 4:'Porcupine', 5:'Sword'}   

nameoffile ='E://file.csv' 
with open(nameoffile, 'wb') as outfile: 
    #makes csv using DictWriter 
    fieldnames = [1,2,3,4,5] 
    writer = csv.DictWriter(outfile, dialect='excel', fieldnames=fieldnames) 
    writer.writeheader()  
    temp = dict() 
    for keys, values in allhands.items(): 
     temp[keys] = values 
    writer.writerow(temp) 
+0

謝謝!在你的例子中,它看起來像缺少的步驟是從字典值創建一個列表,然後只是寫了那個列表。我不太明白temp = dict()在做什麼 - 我從來沒有定義過dict()。那是一個元組嗎? –

0

感謝薩德克,我得到它的工作,但我不明白爲什麼:)

這是令人困惑我的部分是:

temp = dict() 
for keys, values in allhands.items(): 
    temp[keys] = values 
writer.writerow(temp) 

我從未定義字典(),是創建一個元組?

我的功能代碼如下 - 我只是將這個答案插入for循環迭代我的字典的字典。

with open(nameoffile, 'wb') as outfile: #makes csv using DictWriter and list of dict values 
for k, v in allhands.items(): 
    fieldnames = [1,2,3,4,5] 
    writer = csv.DictWriter(outfile, dialect='excel', fieldnames=fieldnames) 
    temp = dict() 
    for keys, values in v.items(): 
     temp[keys] = values 
    writer.writerow(temp) 

第二個問題:在for循環中重新啓動writer是pythonic嗎?我曾假設這將在csv文件中返回一行,並覆蓋自身,並以最後一個字典的內容結束。

但它的工作!只是希望我明白了爲什麼:)

相關問題