使用dict python中的值创建excel文件

时间:2018-01-10 19:32:39

标签: python dictionary xlwt

我有一个下面给出的代码,我想创建一个excel文件。代码是:

#!/usr/bin/python
import xlwt
wb = xlwt.Workbook()
ws = wb.add_sheet('A Test Sheet')
orf = {1: ('793', 804, 12, 0), 2: ('952', 1020, 69, 0), 3: ('1222', 1227, 6, 0), 4: ('1309', 1338, 30, 0), 5: ('1921', 1977, 57, 0), 6: ('2164', 2253, 90, 0), 7: ('2305', 2337, 33, 0)}
ws.write(0, 0, "NO.")
ws.write(0, 1, "Direction")
ws.write(0, 2, "Frame")
ws.write(0, 3, "Start")
ws.write(0, 4, "End")
ws.write(0, 5, "Codon numbers")
ws.write(0, 6, "ORF Sequence")

j = 1
k = 2
for i in orf.items():
    numorf=i[0]
    startorf=orf[numorf][0]
    stoporf=orf[numorf][1]
    lengthorf=orf[numorf][2]
    frameorf=orf[numorf][3]        
    ws.write(j, k, numorf)
    ws.write(j, k, "5 to 3")
    ws.write(j, k, frameorf)
    ws.write(j, k, startorf)  
    ws.write(j, k, stoporf)
    ws.write(j, k, lengthorf)
    ws.write(j, k, "ATGACA...ATGCGA")
    j = j+1
    k = k+1   


wb.save('example.xls')

代码的所有部分都工作正常,但循环中写入字典值的部分不正确并给出以下错误,

for i,j,k in orf.items():
ValueError: need more than 2 values to unpack

我试图解决它但未能这样做。

如何在循环中正确管理列和行号,以便可以使用dict中的值创建文件?

为清楚起见,我想将numorf的值设置为“NO。”,方向下方为“5至3”,“Frame”下方为frameorf,“Start”下方为startorf,“End”下方为stoporf,“lenghtorf”位于“密码子数字“和”ATGACA ...... ATGCGA“低于”ORF序列“。

1 个答案:

答案 0 :(得分:2)

首先,代码段中的for int与错误代码段中的代码段不同。

无论如何,我认为你想要的是:

for row,values in orf.iteritems():
    startorf,stoporf,lengthorf,frameorf = values
    ws.write(row, 0, row)
    ws.write(row, 1, "5 to 3")
    ws.write(row, 2, frameorf)
    ws.write(row, 3, startorf)  
    ws.write(row, 4, stoporf)
    ws.write(row, 5, lengthorf)
    ws.write(row, 6, "ATGACA...ATGCGA")

前两行也可以改写为:

for row,(startorf,stoporf,lengthorf,frameorf) in orf.iteritems(): 
    # note the parenthesis, them make the tuple (the value) expand in the respective variables
    # just write to the worksheet as before
    ws.write(row, 0, row) 
    # ...