# Multiplying all the values in a dictionary

Felipe Almeida Lessa felipe.lessa at gmail.com
Fri Mar 24 03:14:15 CET 2006

```Em Qui, 2006-03-23 às 17:54 -0800, Scott David Daniels escreveu:
> John McMonagle wrote:
> > Say I have a dictionary like below:
> >
> > d = {(100,500):[5,5], (100,501):[6,6], (100,502):[7,7]}
> >
> > Say I want to multiply all the values of the dictionary by 2:
> > for key in d.keys():
> >   d[key] = map(lambda x: x*2, d.get(key))
> > Is there a better/faster/cleaner way to achieve this ?
>
> To update, I'd either go with that or Felipe's list comprehension.
> If you just want the value of the result, how about:
>
>      doubled = dict((key, [x * 2 for x in values])
>                     for key, values in d.iteritems())

And always benchmark:

\$ python2.4 -mtimeit -s 'd = {(100,500):[5,5], (100,501):[6,6],
(100,502):[7,7]}; x = dict(d)' 'for key in d.keys(): x[key] = map(lambda
x: x*2, d.get(key))'
100000 loops, best of 3: 8.48 usec per loop

\$ 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: 3.92 usec per loop

You get a large improvement here because:
- lambdas are slow compared to direct operations:
\$ python2.4 -mtimeit -s 'a = lambda x: x*2' 'a(1)'
1000000 loops, best of 3: 0.411 usec per loop
\$ python2.4 -mtimeit -s 'def a(x): return x*2' 'a(1)'
1000000 loops, best of 3: 0.41 usec per loop
\$ python2.4 -mtimeit '1*2'
10000000 loops, best of 3: 0.16 usec per loop
- d.get(x) is slower than d[x]:
\$ python2.4 -mtimeit -s 'd = {1:1}' 'd'
10000000 loops, best of 3: 0.172 usec per loop
\$ python2.4 -mtimeit -s 'd = {1:1}' 'd.get(1)'
1000000 loops, best of 3: 0.363 usec per loop
- "for key in d:" is faster than "for key in d.keys():":
\$ python2.4 -mtimeit -s 'd = {1:1}' 'for k in d: pass'
1000000 loops, best of 3: 0.345 usec per loop
\$ python2.4 -mtimeit -s 'd = {1:1}' 'for k in d.keys(): pass'
1000000 loops, best of 3: 0.69 usec per loop

\$ python2.4 -mtimeit -s 'd = {(100,500):[5,5], (100,501):[6,6],
(100,502):[7,7]}; x = dict(d)' 'dict((key, [x * 2 for x in values])  for
key, values in d.iteritems())'
100000 loops, best of 3: 7.72 usec per loop

Here it's slower because it creates another dictionary. But it's a
different result, can't be compared directly.

HTH,

--
Felipe.

```