我已经生成了一个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
我很感激你的指导。你知道吗
多亏了萨德格,我才得以成功,但我不太明白为什么:)
让我困惑的是:
我从未定义过dict(),这是在创建元组吗?你知道吗
我的功能代码如下-我只是把这个答案插入到一个for循环中,循环遍历我的dict。你知道吗
第二个问题:在for循环中重新启动writer是pythonic吗?我假设这将返回csv文件中的一行,覆盖它自己,并以最后一个dict的内容结束
但它是有效的!但愿我能明白为什么:)
下面是如何通过DictWriter将Dict写入CSV文件的示例。你知道吗
我觉得这很有帮助。你知道吗
相关问题 更多 >
编程相关推荐