在Python中将列表(不同长度)写入csv

时间:2014-07-24 19:10:49

标签: python csv dictionary

目前,iam正在努力使用列表字典。 给出这样的字典:

GO_list = {'Seq_A': ['GO:1234', 'GO:2345', 'GO:3456'],
   'Seq_B': ['GO:7777', 'GO:8888']}  

不,我想把这个字典写成csv文件 如下:

编辑 我添加了整个功能以提供更多信息

def map_GI2GO(gilist, mapped, gi_to_go):
with open(gilist) as infile:
    read_gi = csv.reader(infile)
    GI_list = {rows[0]:rows[1] for rows in read_gi} # read GI list into dictionary
    GO_list = defaultdict(list) # set up GO list as empty dictionary of lists
    infile.close()
with open(gi_to_go) as mapping:
    read_go = csv.reader(mapping, delimiter=',')         
    for k, v in GI_list.items(): # iterate over GI list and mapping file
        for row in read_go:
            if len(set(row[0]).intersection(v)) > 0 :
                GO_list[k].append(row[1]) # write found GOs into dictionary
                break
    mapping.close()
with open(mapped, 'wb') as outfile: # save mapped SeqIDs plus GOs
    looked_up_go = csv.writer(outfile, delimiter='\t', quoting=csv.QUOTE_MINIMAL)
    for key, val in GO_list.iteritems():
        looked_up_go.writerow([key] + val)
    outfile.close()

然而,这给了我以下输出:

Seq_A,GO:1234; GO2345; GO:3456
Seq_B,GO:7777; GO:8888

我希望将列表条目放在不同的列中,
由定义的分隔符分隔。我很难得到 摆脱;,显然是将列表条目分开。

欢迎任何想法

1 个答案:

答案 0 :(得分:1)

如果我是你,我会尝试使用itertools izip_longest来匹配不同长度的列......

from csv import writer
from itertools import izip_longest

GO_list = {'Seq_A': ['GO:1234', 'GO:2345', 'GO:3456'],
'Seq_B': ['GO:7777', 'GO:8888']}

with open("test.csv","wb") as csvfile:
    wr = writer(csvfile)
    wr.writerow(GO_list.keys())#writes title row
    for each in izip_longest(*GO_list.values()): wr.writerow(each)