Re: Multiplying all the values in a dictionary
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.python archive

Re: Multiplying all the values in a dictionary

From: <adam.deprince@gmail.com>
Date: Fri Mar 24 2006 - 03:01:39 CET

>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]}
Received on Sun Apr 30 21:01:21 2006