Python参数作为字典

Sea*_* W. 43 python dictionary arguments

如何将参数名称及其值作为字典传递给方法?

我想为GET请求指定可选和必需的参数作为HTTP API的一部分,以便构建URL.我不确定制作这种pythonic的最佳方法.

Fre*_*Foo 55

使用前缀为的单个参数**.

>>> def foo(**args):
...     print(args)
...
>>> foo(a=1, b=2)
{'a': 1, 'b': 2}
Run Code Online (Sandbox Code Playgroud)

  • @Marcin:好吧,也许我太容易放弃代码,但这是我在学习语言时总是很难找到的那种结构. (13认同)
  • 只是要添加,单个*用于接受未命名数量的非关键字args作为列表:*args (4认同)
  • 如果我仍然希望在函数定义中提供可能的关键字参数(和默认值)怎么办? (2认同)

Bha*_*udi 36

对于非keyworded参数,使用单个*,对于keyworded参数,使用a **.

例如:

def test(*args, **kwargs):
    print args
    print kwargs

>>test(1, 2, a=3, b=4)
(1, 2)
{'a': 3, 'b': 4}
Run Code Online (Sandbox Code Playgroud)

非keyworded参数将解包为元组,keyworded参数将解压缩到字典. 打开参数列表