在Python中列表到CSV的字典 [英] Dictionary of Lists to CSV in Python
本文介绍了在Python中列表到CSV的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前有一个字典,其值是列表。
I currently have a dictionary who values are lists.
示例: {1:[12,13,14,15],2 :[12,13,14,15],3:[12,13,14,15]}
等等。
有20000个键,每个列表包含80个值。
I have 20000 keys, and each list contains 80 values.
我试图将其输出到CSV文件,但没有运气使用Dictwriter。这是我的代码的一部分:
I am trying to output this into a CSV file, but have had no luck using Dictwriter. Here is part of my code:
for i in range(0, 3):
filetxt = "\\Level_3\\" + nonsbar[i]
filedata = list(csv.reader(open(filetxt,'rb'), delimiter='\t'));
for j in range (1, len(filedata)):
tempid = filedata[j][0]
idind = tempid.index('|')
geneid = tempid[idind+1:len(tempid)]
genecount = filedata[j][1]
nconn[geneid].append(genecount)
for keys in nconn.keys():
nconn[keys] = zip(nconn[keys])
print "convert to table"
nkeys = nconn.keys()
filetxt = open('nonsmoke.csv', 'wb')
nonsmoketab = csv.DictWriter(filetxt, nkeys,delimiter=',')
nonsmoketab.writeheader()
nonsmoketab.writerow(nconn)
我这样得到一个输出:
I get an ouput like this:
114787 114786
[('161.00',), ('985.00',), ('68.00',)] [('9.00',), ('19.00',), ('2.00',)]
I而是要这样:
114787 114786
161 9
985 19
68 2
推荐答案
您可以使用 itertools.izip_longest
来执行此操作,例如:
Do you want to transpose your dictionary of lists? You can do it with itertools.izip_longest
for example:
from itertools import izip_longest
d = {1: [12, 13, 14, 15], 2: [16, 17, 18], 3: [19, 20, 21, 22]}
labels = d.keys()
rows = izip_longest(*d.values())
csv.writer
可序列化回csv:
import StringIO
buf = StringIO.StringIO()
outf = csv.writer(buf)
outf.writerow(labels)
outf.writerows(rows)
print buf.getvalue()
# 1,2,3
# 12,16,19
# 13,17,20
# 14,18,21
# 15,,22
这篇关于在Python中列表到CSV的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文