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.
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()}
You can loop through the keys and update them:
for key, value in d.items():
d[key] = value / 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With