[Tutor] Fast way to access items in a dictionary

Luke Paireepinart rabidpoobear at gmail.com
Thu Jun 18 07:42:24 CEST 2009


> Looks like a simple 'in' is faster both when it's there...
>
> >>> Timer("'D' in  {'D':123}.keys()").timeit()
> 0.93669924584355613
> >>> Timer("'D' in  {'D':123}").timeit()
> 0.34678047105990117
>
> ... and when it isn't...
>
> >>> Timer("'E' in  {'D':123}.keys()").timeit()
> 0.99194670371434768
> >>> Timer("'E' in  {'D':123}").timeit()
> 0.34795386410769424
> >>>

That's because dictionaries are iterable by default, so if you're 
calling keys() you're just adding the overhead of another function call, 
and (I think) also generating a whole list as well (but keys() may 
return an iterable as well.)


More information about the Tutor mailing list