key not found in dictionary

Ben Finney bignose+hates-spam at benfinney.id.au
Tue Aug 22 21:03:10 EDT 2006


"KraftDiner" <bobrien18 at yahoo.com> writes:

> I have a dictionary and sometime the lookup fails...
> it seems to raise an exception when this happens.
> What should I do to fix/catch this problem?
> 
>     desc = self.numericDict[k][2]
> KeyError: 589824   <---- This is the error that is being produced,
> because there is no key
> 589824.

Others have suggested the general solution of using 'try ... except
Foo' for catching a particular exception and dealing with it.

In the specific use case of wanting a default value when a dictionary
doesn't have a particular key, you can also use this:

    >>> foo = {0: "spam", 1: "eggs", 7: "beans"}
    >>> for key in [1, 2, 7]:
    ...     desc = foo.get(key, None)
    ...     print repr(desc)
    ...
    'eggs'
    None
    'beans'

A brief description is at 'help(dict.get)'.

-- 
 \     "The illiterate of the future will not be the person who cannot |
  `\     read. It will be the person who does not know how to learn."  |
_o__)                                                 -- Alvin Toffler |
Ben Finney




More information about the Python-list mailing list