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

bonono at gmail.com bonono at gmail.com
Thu Dec 15 17:14:37 CET 2005


Christopher Subich wrote:
> 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
Would that have a performance impact as it seems that key needs to be
hashed twice or may be += also need to do it twice ? Just curious.




More information about the Python-list mailing list