0

I have a code given below using which I want to create an excel file.The code is:

#!/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')

All part of code is working fine but the part within the loop writing dictionary values is not correct and giving following error,

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

I tried to solve it but failed to do so.

How columns and row numbers can be managed correctly within a loop, so that file can be created with values from dict?

To make it clear I want to put the value of numorf below "NO.","5 to 3" below direction, frameorf below "Frame", startorf below "Start", stoporf below "End",lenghtorf below "Codon numbers" and "ATGACA...ATGCGA" below "ORF Sequence".

1 Answer 1

2

First of all the for int the code snippet is different from the one from the error snippet.

Anyway, I think that what you want is something like:

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")

the first 2 line could also be rewritten in:

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) 
    # ...
Sign up to request clarification or add additional context in comments.

2 Comments

It gives error in case of first code when I use this line ws.write(row, 0, numorf), but when I changed this to ws.write(row, 0, row) it works fine. Thanks for it.
Yes, you're right, I hadn't tested it. I've changed the code to make it correct. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.