[Tutor] Fw: KeyError list?

Kent Johnson kent37 at tds.net
Thu Aug 16 13:58:59 CEST 2007


Rob Andrews wrote:
> Attempting to massage these into files I can process has involved a
> lot of "throw-away" scripting, and I've caught myself doing some
> really questionable things with basic data structures, leading to my
> original question. Dictionary key errors have been the most common
> here lately, popping up in a fairly wide range of circumstances due to
> seemingly random data.

Do you know about dict.get()? It will return None or a default value of 
your choice if a key is missing. Might be helpful...

In [1]: d={1: 2}
In [2]: d[1]
Out[2]: 2
In [3]: d[2]
------------------------------------------------------------
Traceback (most recent call last):
   File "<ipython console>", line 1, in <module>
<type 'exceptions.KeyError'>: 2

In [4]: d.get(2)
(no output, i.e. None)
In [5]: d.get(2, 100)
Out[5]: 100

Kent


More information about the Tutor mailing list