mentby.com
Blog | Jobs | Help | Signup | Login

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?


Shwinn Ricci Thu, 28 Jul 2011 08:56:07 -0700

Did you try printing the contents of scafPositions to see what it contains,
first?

Also, a traceback is helpful.

As far as introspection, which module are you using to read the excel files?
There's at least two that I know of.


James Reynolds Thu, 28 Jul 2011 09:07:44 -0700

http://wiki.python.org/moin/KeyError

I quote:
"Python raises a *KeyError* whenever a dict() object is requested (using the
format a = adict[key]) and the key is not in the dictionary. If you don't
want to have an exception but would rather a default value used instead, you
can use the get() method: "

Walter


Walter Prins Thu, 28 Jul 2011 09:12:49 -0700

From: tutor-bounces+ramit.prasad=jpmchase.com*******] On Behalf Of Shwinn Ricci
Sent: Thursday, July 28, 2011 10:51 AM
To: tutor*******
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]

Ramit

Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

This communication is for informational purposes only. It is not
intended as an offer or solicitation for the purchase or sale of
any financial instrument or as an official confirmation of any
transaction. All market prices, data and other information are not
warranted as to completeness or accuracy and are subject to change
without notice. Any comments or statements made herein do not
necessarily reflect those of JPMorgan Chase & Co., its subsidiaries
and affiliates.

This transmission may contain information that is privileged,
confidential, legally privileged, and/or exempt from disclosure
under applicable law. If you are not the intended recipient, you
are hereby notified that any disclosure, copying, distribution, or
use of the information contained herein (including any reliance
thereon) is STRICTLY PROHIBITED. Although this transmission and any
attachments are believed to be free of any virus or other defect
that might affect any computer system into which it is received and
opened, it is the responsibility of the recipient to ensure that it
is virus free and no responsibility is accepted by JPMorgan Chase &
Co., its subsidiaries and affiliates, as applicable, for any loss
or damage arising in any way from its use. If you received this
transmission in error, please immediately contact the sender and
destroy the material in its entirety, whether in electronic or hard
copy format. Thank you.

Please refer to  http://www.jpmorgan.com/pages/disclosures  for
disclosures relating to European legal entities.

_______________________________________________
Tutor maillist  -  Tutor*******
To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor


Ramit Prasad Thu, 28 Jul 2011 09:31:38 -0700

Or it could be it's not introspecting the formula within excel and his key
is the string "¡*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.


James Reynolds Thu, 28 Jul 2011 09:46:06 -0700

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

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

>
>
> On Thu, Jul 28, 2011 at 12:11 PM, Prasad, Ramit <ramit.prasad*******
> > wrote:
>
>> *From:* tutor-bounces ramit.prasad=jpmchase.com*******[mailto:
>> tutor-bounces ramit.prasad=jpmchase.com*******] *On Behalf Of *Shwinn
>> Ricci
>> *Sent:* Thursday, July 28, 2011 10:51 AM
>> *To:* tutor*******
>> *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 "¡*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*******
> 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.

_______________________________________________
Tutor maillist  -  Tutor*******
To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor


James Reynolds Thu, 28 Jul 2011 12:59:14 -0700



Related Topics

Post a Comment