[Tutor] Key Error

Alan Gauld alan.gauld at btinternet.com
Sun Jul 8 18:45:40 CEST 2007


"Sara Johnson" <sarliz73 at yahoo.com> wrote
>  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.

OK, Then that is telling us that h is a dictionary containing
further dictionaries inside. The error tells us that at least one
of the dictionaries does not have a key 'NEWI'

If this code is supposed to be production strength it is not of good
quality. It should either be defending these dictionary accesses
with a try/except block or it should be using the get() method
of the dictionary to force a default value. (The tests at the end
are poorly written too. If one of my team produced code like
this I'd be having strong words with them!)

Which is the best solution will depend on the situation...

> I have no where else in my code anything pertaining to
> these 4 keys.

Might I suggest grep? :-)

> The first 3 were there, and produce no errors.  I am making
> adjustments to an existing script.  I only have C programming
> knowledge

I hope you have at least basic Python too? Otherwise even
reading the code will be difficult. While Python is easy to read
thats a strictly relative measure!

> so my thought was that it "newi" was just a variable that
> needed to be assigned.

newi is indeed a "just a variable" that is being assigned a value,
but the value does not exist. This is a data error, your problems
lie in the initialisation of the dictionaries coupled to the 
vulnerability
of the code to this kind of error.

> You'll notice the parameters below (i.e., if wssd < -989 ) but
> there is obviously nothing for "newi" at the moment.

Indeed, but there may be further on. Its certainly not involved
in any of these tests.

> The program's only error at the moment seems to be this line:
>
>   newi=h[key]['NEWI']

The program has several errors IMHO but the one that is causing
the interpreter to complain is due to non existent data.
You need to find why that data is missing.
Or, you could find a valid default value and assign that, either
through a try/except block or by uysing a get() instead of
key access.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list