[Tutor] Fast way to access items in a dictionary

Alan Gauld alan.gauld at btinternet.com
Thu Jun 18 10:08:46 CEST 2009


"Elisha Rosensweig" <benshafat at gmail.com> wrote

> if 'someKey' in dict.keys():
>   someData = dict['someKey']
> 
> is there a faster way to do this? 

Faster in terms of execution speed? 
Sure just miss out the test...

> accessing a key that does not exist will
> through an exception, which is just as tiresome...

Tiresome means more code? but its a lot faster in execution 
time since it only affects the result when you have an error.
(Assuming you hit more often than you miss!)

But you can also use get() which will not throw an exception 
and you can provide a default return value for the times 
you miss

>>> d = {1:7,2:9,3:12}
>>> d.get(2,-1)
9
>>> d.get(12,-1)
-1
>>>

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list