basic question, sorry

John Grayson johngrayson at home.com
Mon Aug 21 07:16:26 EDT 2000


In article <39A0FC56.494696A9 at letterror.com>,
  just at letterror.com wrote:
> Will Ware wrote:
> >
> > Ruud de Rooij (*@spam.ruud.org) wrote:
> > > dict.has_key(n)
> >
> > Alternatively:
> >
> > if n in dict.keys():
> >         do stuff
>
> No!! That's a linear search through the keys list. Additionally, this
> key list must be created first. So this is *always* slower.
>
> A valid alternative is:
>
> try:
>     x = dict[n]
> except KeyError:
>     ..key not available..
> else:
>     ..key is available..
>
> If you expect the key to usually be available, the try/except approach
> may be faster, but in general it's better to use has_key().
>
> Just
>

Better to use the dictionary get method if the key is going to be
absent frequently -- get is about 5 times faster than using exception
handling for the absent case (but takes twice as long is the key *is*
present).

    John

     x = dict.get(n, None)


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list