Multiplying all the values in a dictionary
adam.deprince at gmail.com
adam.deprince at gmail.com
Thu Mar 23 21:01:39 EST 2006
>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]}
Remember, d.update takes a sequence of 2 element sequences representing
key/items pairs.
If your dict is something big and ugly that barely fits in ram, or
something larger than your main memory like a dbm file, you can use
generator interpolation on the outside loop to prevent it all from
being held in memory.
<repeating d= from before>
>>> 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]}
More information about the Python-list
mailing list