[Tutor] Key Error

Brian van den Broek broek at cc.umanitoba.ca
Sun Jul 8 08:21:25 CEST 2007


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 "<stdin>", line 1, in <module>
KeyError: '42'
>>> my_dict[17]
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
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


More information about the Tutor mailing list