将字典写入CSV文件 [英] Writing a dictionary to a CSV file

查看:1235
本文介绍了将字典写入CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

从CSV文件创建一个字典

尝试将字典打印到CSV文件时,我遇到问题。该字典目前有4列,但所有4列打印在1个单列。可能是我用于写入CSV文件的for循环是责备,但我不太确定。我试图在每一列中打印字典。

I am having an issue when trying to print a dictionary to a CSV file. The dictionary currently has 4 columns but all 4 columns are printed in 1 single column. It may be the for loop that I am using to write to the CSV file is to blame but I am not quite sure. I am trying to have the dictionary print in each column.

样本数据:

     Date        First Name     Last Name     Score
12/28/2012 15:15        John          Smith        20
12/29/2012 15:15        Alex          Jones        38
12/30/2012 15:15      Michael       Carpenter      25

以下是一些代码摘录:

import csv

csvWriter = csv.writer(open("C:\\Users\\Chris\\Desktop\\test_out.csv", 'w'), delimiter=' ', quotechar=' ', quoting=csv.QUOTE_MINIMAL)

阅读上面的CSV文件:

For loop to read in CSV file above:

读者中的行:

for k, v in row.items():

    if not k in mydict:
        mydict[k] = [v]
    else:
        mydict[k].append(v)

用于循环将Dictionary键打印到CSV文件。

For loop to print Dictionary keys to CSV file.

for item in mydict.keys():
    csvWriter.writerow(item)

当前输出(列标题):

D a t e

F i r s t    N a m e

L a s t      N a m e

S c o r e

想要输出(列标题):

Date      First Name       Last Name       Score

任何帮助非常感谢。

推荐答案

现在我更了解你的结构,尝试这样:

Now that I understand your structure better, try this:

#first write column headers
csvWriter.writerow(list(mydict.keys())

#now data, assuming each column has the same # of values
for i in xrange(len(mydict['Date'])):
    csvWriter.writerow([mydict[k][i] for k in mydict.keys()])

这篇关于将字典写入CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆