簡體   English   中英

Python列表中的CSV列表

[英]Dictionary of Lists to CSV in Python

我目前有一個字典,其值是列表。

例如: {1: [12, 13, 14, 15], 2: [12, 13, 14, 15], 3: [12, 13, 14, 15]}等等。

我有20000個密鑰,每個列表包含80個值。

我試圖將其輸出為CSV文件,但使用Dictwriter沒有運氣。 這是我的代碼的一部分:

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)

我得到這樣的輸出:

114787  114786  
[('161.00',), ('985.00',), ('68.00',)]  [('9.00',), ('19.00',), ('2.00',)]

我反而想要這個:

114787 114786   
161     9
985     19
68      2

你想轉置你的名單字典嗎? 您可以使用itertools.izip_longest執行此操作,例如:

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

我可以給你一個粗略的建議:從csv.DictWriter實現,覆蓋方法writerow(self, rowdict)writerows(self, rowdicts) ,在self._dict_to_list(rowdict)的結果中添加循環(在你的情況下是它的列表)這兩個功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM