Multiplying all the values in a dictionary

Scott David Daniels scott.daniels at acm.org
Fri Mar 24 02:54:23 CET 2006


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())

-- 
-Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list