将函数映射到字典中指定键的值 [英] Map a function to values of specified keys in dictionary
问题描述
是否有方便的方法将功能映射到字典中的指定键?
Is there a convenient way to map a function to specified keys in a dictionary?
即给定
d = {"a": 1, "b": 2, "c": 3}
想将一个函数(例如f)映射到键 a和 c:
would like to map a function, say f, to keys "a" and "c":
{"a": f(1), "b": 2, "c": f(3)}
编辑
正在寻找不会更新输入字典的方法。
Looking for methods that will not update the input dictionary.
推荐答案
您可以使用字典理解:
output_dict = {k: f(v) for k, v in d.items()}
f(v)
将被立即求值(调用),其返回值将作为字典的值存储。
Note that f(v)
will be evaluated (called) immediately and its return values will be stored as the dictionary's values.
如果要存储该函数并在以后调用它(已存储参数),则可以使用 functools.partial
:
If you want to store the function and call it later (with the arguments already stored) you can use functools.partial
:
from functools import partial
def f(n):
print(n * 2)
d = {"a": 1, "b": 2, "c": 3}
output_dict = {k: partial(f, v) for k, v in d.items()}
output_dict['b']()
# 4
如果您只想要特定键映射后,您当然不能使用 .items
并仅覆盖这些键:
If you only want specific keys mapped you can of course not use .items
and just override those keys:
d['a'] = partial(f, d['a'])
或更为笼统的
keys = ('a', 'c')
for key in keys:
d[key] = partial(f, d[key])
这篇关于将函数映射到字典中指定键的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!