Optimize function similiar to dict.update() but adds common values

Christopher Subich csubich.spam.block at spam.subich.block.com
Thu Dec 15 11:00:02 EST 2005


Peter Otten wrote:
> 
> def add_freqs3(freq1, freq2):
>     total = dict(freq1)
>     for key, value in freq2.iteritems():
>         try:
>             total[key] += value
>         except KeyError:
>             total[key] = value
>     return total
> 

Untested, but replacing the try/except pair with the following should be 
semantically equivalent and a bit faster:

total[key] = total.get(key,0) + value



More information about the Python-list mailing list