Modify dict values inplace

懵懂的女人 提交于 2021-02-17 19:16:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!