这就是你想要的吗?def func(**kwargs):
for key, value in kwargs.items():
pass # Do something
func(**myDict) # Call func with the given dict as key/value parameters
(有关关键字参数的详细信息,请参见documentation)。myDict中的键必须是字符串。)
编辑:您编辑了问题以包括以下内容:I think the ** notation in front of myDict instructs the function to expect a dictionary and to unpack the key (the first *) and the value, the second *
这是不对的。要了解发生了什么,您必须考虑以下因素:一个函数可以有多个形式参数(在这种情况下,a和b):def f1(a, b): pass我们可以将位置参数传递给这样的函数(与大多数其他语言一样):f1(2, 3)我们还可以传递关键字参数:f1(a=2, b=3)我们也可以混合这些,但是位置参数必须首先出现:f1(2, b=3)
f1(a=2, 3) # SyntaxError: non-keyword arg after keyword arg有一种方法可以让函数接受任意数量的位置参数,它可以作为元组访问这些参数(在这种情况下,args):def f2(*args): assert isinstance(args, tuple)现在,我们可以使用单独指定的参数调用f2,或者使用一个列表,该列表的内容首先需要被解压,语法类似于*args:f2(2, 3)
f2(*[2, 3])同样,可以接受任意数量的关键字参数:def f3(**kwargs): pass注意,f3不要求类型为dict的单个参数。这是它期望的调用类型:f3(a=2, b=3)
f3(**{'a': 2, 'b': 3})f3的所有参数都必须命名为:f3(2, 3) # TypeError: f3() takes exactly 0 arguments (2 given)
把所有这些放在一起,并记住位置论必须放在第一位,我们可能有:>>> def f4(a, b, *args, **kwargs):
... print('%r, %r' % (args, kwargs))
...
>>> f4(2, 3)
(), {}
>>> f4(2, 3, 4, 5)
(4, 5), {}
>>> f4(2, 3, x=4, y=5)
(), {'y': 5, 'x': 4}
>>> f4(2, 3, 4, 5, x=6, y=7)
(4, 5), {'y': 7, 'x': 6}
>>> f4(2, *[3, 4, 5], **{'x': 6, 'y': 7})
(4, 5), {'y': 7, 'x': 6}
请特别注意以下两个错误:>>> f4(2)
Traceback (most recent call last):
File "", line 1, in
TypeError: f4() takes at least 2 arguments (1 given)
>>> f4(2, 3, a=4)
Traceback (most recent call last):
File "", line 1, in
TypeError: f4() got multiple values for keyword argument 'a'
第二个错误应该有助于解释这种行为:>>> f4(**{'foo': 0, 'a': 2, 'b': 3, 'c': 4})
(), {'c': 4, 'foo': 0}