[Tutor] Key Error

Sara Johnson sarliz73 at yahoo.com
Sun Jul 8 18:10:32 CEST 2007


 
  Probably best if I skip the example and show what code I do have:
  ~~~~~~~~~~~
  for key in h.keys():
        wssd=h[key]['WSSD']
        wspd=h[key]['WSPD']
        wmax=h[key]['WMAX']
        newi=h[key]['NEWI']
        if wssd<-989. or wspd<-989. or wmax<-989.: break
        if wspd==0.: break
~~~~~~~~~~~~~~~~~
  Where the "newi" = "abcd" that I showed before.  I have no where else in my code anything pertaining to these 4 keys.  The first 3 were there, and produce no errors.  I am making adjustments to an existing script.  I only have C programming knowledge so my thought was that it "newi" was just a variable that needed to be assigned.  You'll notice the parameters below (i.e., if wssd < -989 ) but there is obviously nothing for "newi" at the moment.  The program's only error at the moment seems to be this line:
   
   newi=h[key]['NEWI']

  But as you can see, the other items are set up the same way.
   
  Thanks bundles!!!  
  Sara

  Message: 7
Date: Sun, 08 Jul 2007 02:21:25 -0400
From: Brian van den Broek 

Subject: Re: [Tutor] Key Error
To: sarliz73 at gmail.com
Cc: tutor at python.org
Message-ID: <46908265.7030205 at cc.umanitoba.ca>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed

Sara Johnson said unto the world upon 07/08/2007 01:34 AM:
> Sorry, this is probably too general a question, but I can't find
> any specific information on it. What exactly is a "key error" and
> how do I clear it?
> 
> I entered something like this:
> 
> abcd=h[key]['ABCD']
> 
> and when I run it I'm getting
> 
> KeyError: 'ABCD'
> 
> What does this mean?
> 
> Thanks!
> 


Hi Sara,

It means you've tried to access a data structure (most likely a
dictionary) with a key that does not exist in that structure. Witness

>>> my_dict={42:"Six times seven", 1: "The loneliest number"} 
>>> my_dict[42]
'Six times seven'
>>> my_dict['42']
Traceback (most recent call last):
File "", line 1, in 
KeyError: '42'
>>> my_dict[17]
Traceback (most recent call last):
File "", line 1, in 
KeyError: 17
>>> 

It isn't a question of `clearing' it, but of tracking down the wrong
assumption behind your code. It may be that you thought you were using
a key you'd added before and were wrong (my_dict['42'] as opposed to
my_dict[42] shows a common source of that).

But, from your

> abcd=h[key]['ABCD']

I'm guessing that you've got the key-access syntax a bit wrong. Did 
you mean

abcd = h['ABCD']

instead?

HTH,

Brian vdB

 
---------------------------------
Don't get soaked.  Take a quick peak at the forecast 
 with theYahoo! Search weather shortcut.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070708/5ecf5259/attachment.html 


More information about the Tutor mailing list