Append a new value to dict

bearophileHUGS at bearophileHUGS at
Thu Oct 23 23:27:36 CEST 2008


> Slower than
> ...

Okay, I seen there's a little confusion, I try to say it more clearly.
Generally this is the faster version (faster than the version with
get), especially if you use Psyco:

version 1)
if 'B' in counter:
    counter['B'] += 1
    counter['B'] = 1


Version using a defaultdict:
version 2)
counter['B'] += 1 #

The defaultdict case 2) is intermediate: its relative speed changes on
the basis of the frequency of already present keys. Generally the
difference between 1) and 2) isn't much, so I usually use a
defaultdict 2), that has a nicer syntax, even if it can sometimes be a
little slower than 1).

Versions with has_key or try-except or get aren't fast.


More information about the Python-list mailing list