Python 就地修改字典值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15536623/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:21:24  来源:igfitidea点击:

Modify dict values inplace

pythonmapdictionaryfunctional-programming

提问by Qortex

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

我想将函数应用于dictinplace 中的值dict(例如map在函数式编程设置中)。

Let's say I have this dict:

假设我有这个dict

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

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

我想将该函数divide by 2.0应用于 dict 的所有值,导致:

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

What is the simplest way to do that?

最简单的方法是什么?

I use Python 3.

我使用Python 3

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

编辑:单线会很好。这divide by 2只是一个例子,我需要函数作为参数。

采纳答案by John La Rooy

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()}

回答by jamylak

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

回答by Brendan Long

You can loop through the keys and update them:

您可以遍历键并更新它们:

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

回答by Ishpeck

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}