gpt4 book ai didi

python - 将字典作为关键字参数传递给函数

转载 作者:IT老高 更新时间:2023-10-28 12:07:40 26 4
gpt4 key购买 nike

我想在 python 中使用具有匹配参数键值对的字典来调用函数。

这里有一些代码:

d = dict(param='test')

def f(param):
print(param)

f(d)

这会打印 {'param': 'test'} 但我希望它只打印 test

我希望它对更多参数有类似的工作:

d = dict(p1=1, p2=2)
def f2(p1, p2):
print(p1, p2)
f2(d)

这可能吗?

最佳答案

最后自己想通了。很简单,我只是缺少 ** 操作符来解包字典

所以我的例子变成了:

d = dict(p1=1, p2=2)
def f2(p1,p2):
print p1, p2
f2(**d)

关于python - 将字典作为关键字参数传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/334655/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com