Append a new value to dict
bearophileHUGS at lycos.com
bearophileHUGS at lycos.com
Thu Oct 23 17:27:36 EDT 2008
slais-www:
> 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
else:
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.
Bye,
bearophile
More information about the Python-list
mailing list