Way for see if dict has a key

Bruno Desthuilliers onurb at xiludom.gro
Fri Jun 30 08:55:15 EDT 2006


Fredrik Lundh wrote:
> "André" wrote:
> 
> 
>>Perhaps Bruno meant this:
>>
>>try:
>>   ... my_dict[key] ...
>>except:
>>...
>>
>>when we expect that the key will most often be in my_dict so that
>>exception will be raised rarely, otherwise use
> 
> 
> on my machine, "key in dict" is about twice as fast as the full try/getitem con-
> struct when the key is present in the dict,

Doesn't it depends on the number of keys in the dict ?

> so that's not a very good optimization.

FWIW, I personaly didn't meant to present it as an optimisation - just
as one more possible way to test the existence of a given key...

> now, if the OP had been interested in the associated value, things might have
> been a bit different.
> 
> </F> 
> 
> 
> 


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list