问题
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.
回答1:
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()}
回答2:
You can loop through the keys and update them:
for key, value in d.items():
d[key] = value / 2
回答3:
Should work for you:
>>> d = {'a':2.0, 'b':3.0}
>>> for x in d:
... d[x]/=2
...
>>> d
{'a': 1.0, 'b': 1.5}
回答4:
>>> d = { 'a': 2, 'b': 3 }
>>> {k: v / 2.0 for k, v in d.items()}
{'a': 1.0, 'b': 1.5}
来源:https://stackoverflow.com/questions/15536623/modify-dict-values-inplace