[Tutor] Fwd: KeyError?

James Reynolds eire1130 at gmail.com
Thu Jul 28 21:53:26 CEST 2011


---------- Forwarded message ----------
From: Shwinn Ricci <armvrt at gmail.com>
Date: Thu, Jul 28, 2011 at 1:13 PM
Subject: Re: [Tutor] KeyError?
To: James Reynolds <eire1130 at gmail.com>




On Thu, Jul 28, 2011 at 12:42 PM, James Reynolds <eire1130 at gmail.com> wrote:

>
>
> On Thu, Jul 28, 2011 at 12:11 PM, Prasad, Ramit <ramit.prasad at jpmchase.com
> > wrote:
>
>> *From:* tutor-bounces+ramit.prasad=jpmchase.com at python.org [mailto:
>> tutor-bounces+ramit.prasad=jpmchase.com at python.org] *On Behalf Of *Shwinn
>> Ricci
>> *Sent:* Thursday, July 28, 2011 10:51 AM
>> *To:* tutor at python.org
>> *Subject:* [Tutor] KeyError?****
>>
>> ** **
>>
>> I have an excel file that I am reading cell values from and putting them
>> into a dictionary. the dictionary looks like this:
>>
>> scafPositions = {position[j]: direction[j]}
>>
>> where position[j] is exclusively floating/numerical values and
>> direction[j] is exclusively strings.
>>
>> When I try to find whether a test value val is in the array of positions,
>> and then try to look its direction up with ScafPositions[val], I get a
>> KeyError. Is this because my data isn't standalone numbers, but numbers that
>> are calculated based off other cells? Or can I not test for val?****
>>
>> ======================================****
>>
>> ** **
>>
>> Your problem is probably that you are reassigning a new dictionary to the
>> name scafPositions each time instead of updating it. You should have
>> something like the following.****
>>
>> ** **
>>
>> scafPositions = {}****
>>
>> ** **
>>
>> #loop structure here:****
>>
>>     #do stuff****
>>
>>     scafPositions[ position[j] ] = direction[j]****
>>
>>
>>
>
> this is my code:
>

def LookUp(helix, scafPos):

 # create dictionaries (keyed by vstrand #) of
 # scaffold position with value representing orientation

        book = xlrd.open_workbook('CoordinatesSpreadsheet.xls')
        sheet = book.sheet_by_index(0)
        cols = sheet.row_values(2,1,150)
       9
        position = {}
        direction = {}
        scafPositions = {}
        for i in range(len(cols)):
            rows = sheet.col_values(i+2, 5, 500)

            #create lists of position and direction, sets up dictionary
            for j in range(len(rows)):
                          position[j] = float(sheet.cell(j+5, i+3).value)
                          direction[j] = sheet.cell(j+5, i+1).value

                          scafPositions[position[j]] = direction[j]
            i += 5


   #returns value for appropriate caDNAno position, which is represented as
a concatenation of the input helix and scaffold position
        val = float(helix) + (float(scafPos) * 0.001)

        if (scafPositions[val] == "out"):
           print "Warning: Base pointing outwards"



        return scafPositions[val]


def main(argv):
    return LookUp(sys.argv[1], sys.argv[2])


if __name__ == "__main__":
    main(sys.argv[1:])

perhaps im on the wrong sheet? all the tutorials say "sheet0" but I'm on
openoffice and the first sheet is 'sheet1'

>
> Or it could be it's not introspecting the formula within excel and his key
> is the string "=A1*sheet2!$B$1"or it could be he's looking for a float / int
> when in reality it's a string (because it must be converted explicitly).
>
> Without a traceback and the code, it's hard to know for sure.
>
> My guess is leading towards introspection.
>
> As far as printing the contents, once you create your dict with all the
> data just use the print statement / function depending on your version of
> python
>
> print scafPositions or print(scafPositions)
>
> You could loop through it as well
>
> for key, value in scafPositions.items():
>     print key, value
>
> This will give you an idea of what is in the dict.
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

Sending this whole thing to the entire list. You should send replies to the
list as well.

going to go bit by bit here:


def LookUp(helix, scafPos):
>         book = xlrd.open_workbook('CoordinatesSpreadsheet.xls')
>         sheet = book.sheet_by_index(0)


ok good so far (but don't capitalize functions)

        cols = sheet.row_values(2,1,150)


Here you are getting a slice of columns, from a single row. About 149
columns worth.

        position = {}
>         direction = {}


You don't need these dictionaries for anything useful as far as I can tell,
so drop them

        for i in range(len(cols)):
>             rows = sheet.col_values(i+2, 5, 500)


This doesn't make sense with the above, you are now taking a slice of rows
from a single column. I would probably rewrite this (i'll give you a
suggestion in a moment)

            for j in range(len(rows)):
>                 position[j] = float(sheet.cell(j+5, i+3).value)
>                 direction[j] = sheet.cell(j+5, i+1).value
>                 scafPositions[position[j]] = direction[j]
>             i += 5



Ok, so position isn't a dict anymore. Just make position a straight variable
(position = float(sheet.cell(j+5, i+3).value)) and the same with direction,
like this:

            for j in range(len(rows)):
>                 position = float(sheet.cell(j+5, i+3).value)
>                 direction = sheet.cell(j+5, i+1).value
>                 scafPositions[position] = direction
>             i += 5


I'm a big fan of naming things, even when you don't need them, but
technically you don't need the direction variable. You could just do:


            for j in range(len(rows)):
>                 position = float(sheet.cell(j+5, i+3).value)
>                 scafPositions[position] = sheet.cell(j+5, i+1).value
>             i += 5


The  i += 5 doesn't make much sense to me.

Your saying the data you want is in each fifth column relative to the next
column in "cols". So, if it's on column 4, the next column looked at would
be 9, 14, etc. Once those rows are complete, it will look at 5,10,15 etc,
prior to the offsets.

        val = float(helix) + (float(scafPos) * 0.001)


How do you know that this calculation exists the spreadsheet? Can you be
assured of it, 100% of the time with no failures?

        if (scafPositions[val] == "out"):
>             print "Warning: Base pointing outwards"



Without seeing your traceback, I'll bet this is where its throwing the
error.

I would probably have it more like this:

def lookup(helix, scafPos):
>  # create dictionaries (keyed by vstrand #) of
>  # scaffold position with value representing orientation
>
>         book = xlrd.open_workbook('CoordinatesSpreadsheet.xls')
>         sheet = book.sheet_by_index(0)
>         scafPositions = {}
>         for i in range(sheet.ncols)[1:150]: #ncols and nrows is a builtin
> to this module, returning the count of total rows or columns.
>             #range is a list, so you can just take a slice of that.
>             for j in range(sheet.nrows)[5:500]:
>                 position = float(sheet.cell(j+5, i+3).value) #I'm going to
> assume you want to look at the cell five down and 3 to the right from this
>                 direction = sheet.cell(j+5, i+1).value
>                 scafPositions[position] = direction
>                 print scafPositions #only one run once, the delete this
> line
>                 break # only run once with this line, then delete.
>             i += 5 #Are you sure this is what you want?
>
>         val = float(helix) + (float(scafPos) * 0.001)
>         if (scafPositions[val] == "out"):
>             print "Warning: Base pointing outwards"
>

 I use xlrd and xlwt all the time, but if you want to learn python, it might
not be the best way to go about it.

I am nearly 100% certain that xlrd can not calculate cell contents for you.
What I do is copy and past the values only into the sheet,and then run
python.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110728/aabd67e5/attachment-0001.html>


More information about the Tutor mailing list