Multiplying all the values in a dictionary

Scott David Daniels scott.daniels at acm.org
Thu Mar 23 20:54:23 EST 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