gpt4 book ai didi

python - 将命名参数打包到字典中

转载 作者:太空狗 更新时间:2023-10-29 21:37:08 29 4
gpt4 key购买 nike

我知道如果函数接受 **kwargs,我可以将函数参数转换成字典。

def bar(**kwargs):
return kwargs

print bar(a=1, b=2)
{'a': 1, 'b': 2}

然而,事实恰恰相反吗?我可以将命名参数打包到字典中并返回它们吗?手工编码的版本如下所示:

def foo(a, b):
return {'a': a, 'b': b}

但似乎必须有更好的方法。请注意,我试图避免在函数中使用 **kwargs(命名参数更适合具有代码完成功能的 IDE)。

最佳答案

听起来你在找locals :

>>> def foo(a, b):
... return locals()
...
>>> foo(1, 2)
{'b': 2, 'a': 1}
>>> def foo(a, b, c, d, e):
... return locals()
...
>>> foo(1, 2, 3, 4, 5)
{'c': 3, 'b': 2, 'a': 1, 'e': 5, 'd': 4}
>>>

但是请注意,这将返回 所有 foo 范围内名称的字典:

>>> def foo(a, b):
... x = 3
... return locals()
...
>>> foo(1, 2)
{'b': 2, 'a': 1, 'x': 3}
>>>

如果您的功能与问题中给出的功能一样,这应该不是问题。但是,如果是,您可以使用 inspect.getfullargspec和一个 dictionary comprehension过滤 locals():

>>> def foo(a, b):
... import inspect # 'inspect' is a local name
... x = 3 # 'x' is another local name
... args = inspect.getfullargspec(foo).args
... return {k:v for k,v in locals().items() if k in args}
...
>>> foo(1, 2) # Only the argument names are returned
{'b': 2, 'a': 1}
>>>

关于python - 将命名参数打包到字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26496206/

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