Change dict values ​​in place

I would like to apply a function to a dictinplace values ​​in dict(for example, mapin setting up functional programming).

Let's say I have this dict:

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

I want to apply a function divide by 2.0to all dict values, which results in:

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

What is the easiest way to do this?

I am using Python 3.

Edit: One liner would be nice. divide by 2is just an example, I need a function as a parameter.

+5
source share
4 answers

You may find multiplying is still faster than dividing

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

For inplace version

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

In general

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

d2 = {k: f(v) for k, v in d.items()}
+6
source

You can scroll through the keys and update them:

for key, value in d.items():
    d[key] = value / 2
+15

:

>>> d = {'a':2.0, 'b':3.0}
>>> for x in d:
...     d[x]/=2
... 
>>> d
{'a': 1.0, 'b': 1.5}
+8
>>> d = { 'a': 2, 'b': 3 }
>>> {k: v / 2.0 for k, v in d.items()}
{'a': 1.0, 'b': 1.5}
+3

All Articles