Python 如何使用DictWriter将str值转换为csv,每行有多个值

Python 如何使用DictWriter将str值转换为csv,每行有多个值,python,csv,Python,Csv,我已经生成了一个dict的dict,每个dict包含5个随机生成的字符串元素 我试图将每个dict输出到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:

我已经生成了一个dict的dict,每个dict包含5个随机生成的字符串元素

我试图将每个dict输出到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])
输出如下所示:

[“蜘蛛”“宇宙飞船”“邪恶”“豪猪”“剑”]

[“火车”“相扑选手”“看到”“玻璃”“机器人”]

[“蜜蜂”“大炮”“房子”“T.N.T”“相扑选手”]

[‘空中’‘蜘蛛’‘风’‘太空船’‘辛辣’]

[“海龟”“圣诞老人”“汽车”“飞机”“云”]

我的目标是获得如下输出:

蜘蛛飞船邪恶豪猪剑

训练相扑摔跤手锯玻璃机器人

蜜蜂大炮屋T.N.T相扑选手

空中蜘蛛风飞船

乌龟圣诞老人汽车飞机云

我正在与DictWriter抗争——有没有一种更干净、更通俗的方法来实现这一点?我现在在这里:

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


我感谢任何指导

下面是一个如何通过DictWriter将Dict写入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)

多亏了萨德格,我才得以成功,但我不太明白为什么:)

让我困惑的是:

temp = dict()
for keys, values in allhands.items():
    temp[keys] = values
writer.writerow(temp)
我从未定义过dict(),这是在创建元组吗

下面是我的功能代码——我只是将这个答案插入到一个for循环中,循环遍历我的dict

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文件中的一行,覆盖了它自己,并以最后一条dict的内容结束


但它是有效的!但愿我能理解为什么:)

谢谢!从您的示例来看,缺少的步骤似乎是从dict值创建一个列表,然后只写下该列表。我不太明白temp=dict()在做什么——我从未定义过dict()。那是一个元组吗?