Multiplying all the values in a dictionary

Felipe Almeida Lessa felipe.lessa at gmail.com
Thu Mar 23 21:18:51 EST 2006


Em Qui, 2006-03-23 às 18:01 -0800, adam.deprince at gmail.com escreveu:
> >for key in d:
> >       d[key] = [x*2 for x in d[key]]
> >
> 
> Naw, if you are going to use list interpolation go all the way and save
> yourself all of that ugly indexing into the dict.
> 
> >>> d = {(100,500):[5,5], (100,501):[6,6], (100,502):[7,7]}
> >>> d.update( [[key,[x*2 for x in item]] for key,item in d.items()] )
> >>> d
> {(100, 501): [12, 12], (100, 500): [10, 10], (100, 502): [14, 14]}

No dice. It's uglier IMO and slower IPO:

$ 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.84 usec per loop

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

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

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


PS.:  IPO == In Python's Opinion

-- 
Felipe.




More information about the Python-list mailing list