On Mar 27, 1:06 pm, Duncan Booth <duncan.bo...@invalid.invalid> wrote:
> Carl Banks <pavlovevide...@gmail.com> wrote:
> > On Mar 27, 11:20 am, Paul Rubin <http://phr...@nospam.invalid> wrote:
> >> Carl Banks <pavlovevide...@gmail.com> writes:
> >> > >      if x in theDict:
> >> > >           print x, v
>
> >> > Where does v come from?
>
> >> Oops, pasted from original.  Meant of course "print x, theDict[x]".
>
> > You have look up x twice with that code, whereas you wouldn't have to
> > with this:
>
> > v = theDict.get(x)
> > if v is not None:
> >     print x, v
>
> Note that while you only lookup x in the dict once your code does still
> involve two dict lookups: once to lookup the get method and once to lookup
> x. It also involves creating a new bound method object so if performance is
> a concern you'll find that either the 'if x in theDict: ...' or the
> try...except are likely to be faster.

Not necessarily: if the hash calculation for x is expensive enough the
get version would still be faster.  If all you're doing is looking up
strings or ints (as the OP is doing) it's hardly going to matter
either way.


Carl Banks
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to