如何使用具有多个值的DictWriter将str值转换成csv

2024-04-27 14:39:31 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我试图将每个dict输出到csv文件中的一行,只使用“clean”字符串值,不使用引号或括号。你知道吗

从这个开始:

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])

输出如下所示:

['Spider' 'Spaceship' 'Evil' 'Porcupine' 'Sword']

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

['Bees' 'Cannon' 'House' 'T.N.T' 'Sumo Wrestler']

['Air' 'Spider' 'Wind' 'Spaceship' 'spicy']

['Turtle' 'Santa Claus' 'Car' 'Airplane' 'Cloud']

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

Spider Spaceship Evil Porcupine Sword

Train Sumo Wrestler Saw Glass Robot

Bees Cannon House T.N.T Sumo Wrestler

Air Spider Wind Spaceship spicy

Turtle Santa Claus Car Airplane Cloud

我正在努力与DictWriter-有没有一个更干净,pythonic的方法来实现这一点?我现在在这里:

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

我很感激你的指导。你知道吗


Tags: ofcsvkeyinforvaluewithdict
2条回答

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

让我困惑的是:

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的内容结束

但它是有效的!但愿我能明白为什么:)

下面是如何通过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)

相关问题 更多 >