Dictionaries and incrementing keys

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Jun 14 09:26:49 EDT 2011


On Tue, 14 Jun 2011 12:53:11 +0000, Steve Crook wrote:

> On Tue, 14 Jun 2011 05:37:45 -0700 (PDT), AlienBaby wrote in Message-Id:
> <078c5e9a-8fad-4d4c-b081-f69d0f57593d at v11g2000prk.googlegroups.com>:
> 
>> How do those methods compare to the one I normally use;
>>
>> try:
>>  dict[key]+=1
>> except:
>>  dict[key]=1
> 
> This is a lot slower in percentage terms.  You should also qualify the
> exception: except KeyError

Not necessarily. It depends on how often you have KeyError.

By my measurements, if the key is usually present, it is faster to use 
try...except. Only if the key is frequently missing does it become faster 
to test first.


-- 
Steven



More information about the Python-list mailing list