Multiplying all the values in a dictionary

Adam DePrince adam.deprince at gmail.com
Fri Mar 24 00:23:19 EST 2006


Wait!  It occured to me.  Why are we touching the key at all.  This is
a dictionary with mutable values.

[adam at localhost ~]$ python2.4 -mtimeit -s 'd = {(100,500):[5,5],
(100,501):[6,6],
(100,502):[7,7]}; x = dict(d)' 'for i in x.values():
 i[:]=[j*1 for j in i]'
100000 loops, best of 3: 2.79 usec per loop

And the best from above:
 python2.4 -mtimeit -s 'd = {(100,500):[5,5], (100,501):[6,6],
> (100,502):[7,7]}; x = dict(d)' 'for key in d: x[key] = [y*2 for y in
> d[key]]'
100000 loops, best of 3: 2.85 usec per loop

Now, we *know* that all of the values are lists of length 2, so why not
say this instead:

 python2.4 -mtimeit -s 'from numarray import array; d =
{(100,500):[5,5], (100,501):[6,6],
(100,502):[7,7]}; x = dict(d);j=[0,0]' 'for i in x.values():
 j[0]*=1;j[1]*=1'
1000000 loops, best of 3: 1.7 usec per loop


Of course, the real code would use *=2, but just to be sure that there
is no multiple by 1 optimization:
[adam at localhost ~]$ python2.4 -mtimeit  'h=1;h*=2'
10000000 loops, best of 3: 0.143 usec per loop
[adam at localhost ~]$ python2.4 -mtimeit  'h=1;h*=1'
10000000 loops, best of 3: 0.144 usec per loop




More information about the Python-list mailing list