[Tutor] Fast way to access items in a dictionary

Emile van Sebille emile at fenx.com
Thu Jun 18 05:33:11 CEST 2009


On 6/17/2009 5:39 PM Elisha Rosensweig said...
> Hi,
> 
> Till now, when I receive a dictionary that I'm not sure contains a 
> certain key, I would use the following template to access a given key:
> 
> if 'someKey' in dict.keys():
>    someData = dict['someKey']
> 
> is there a faster way to do this? 

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
 >>>

Emile

> accessing a key that does not exist 
> will through an exception, which is just as tiresome...
> 
> Thanks
> 
> Elisha
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list