key not found in dictionary

Sion Arrowsmith siona at chiark.greenend.org.uk
Wed Aug 23 06:54:08 EDT 2006


Chaz Ginger  <cginboston at hotmail.com> wrote:
>KraftDiner wrote:
>>     desc = self.numericDict[k][2]
>> KeyError: 589824   <---- This is the error that is being produced,
>As stated you can wrap the access in the try - except - else statement, 
>as in
>
>try:
>  foo['bar']
>except :
>  # Handle the error.

Bare "except" is generally a bad idea. Here, it could be letting
through whole truckloads of other errors. Suppose the OP typos:

try:
    desc = self.numericDict[j][2]
except:
    # handle missing key

but the except isn't handling a KeyError, it's got a NameError
(assuming j doesn't exist). Or what if self.numericDict[k] exists
but self.numericDict[k][2] gives a TypeError or IndexError? It
really needs to be:

except KeyError:

-- 
\S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
  ___  |  "Frankly I have no feelings towards penguins one way or the other"
  \X/  |    -- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump



More information about the Python-list mailing list