Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify dict values inplace

I would like to apply a function to values of a dict inplace in the dict (like map in a functional programming setting).

Let's say I have this dict:

d = { 'a':2, 'b':3 }

I want to apply the function divide by 2.0 to all values of the dict, leading to:

d = { 'a':1., 'b':1.5 }

What is the simplest way to do that?

I use Python 3.

Edit: A one-liner would be nice. The divide by 2 is just an example, I need the function to be a parameter.

like image 960
Qortex Avatar asked Mar 20 '13 23:03

Qortex


2 Answers

You may find multiply is still faster than dividing

d2 = {k: v * 0.5 for k, v in d.items()}

For an inplace version

d.update((k, v * 0.5) for k,v in d.items())

For the general case

def f(x)
    """Divide the parameter by 2"""
    return x / 2.0

d2 = {k: f(v) for k, v in d.items()}
like image 126
John La Rooy Avatar answered Sep 17 '22 18:09

John La Rooy


You can loop through the keys and update them:

for key, value in d.items():
    d[key] = value / 2
like image 21
Brendan Long Avatar answered Sep 21 '22 18:09

Brendan Long