尝试将字典传递到函数中以将其打印出来,但会引发错误:mosp_courses((获取0个位置参数,但给出了1个
def most_courses(**diction):
for key, value in diction.items():
print("{} {}".format(key,value))
most_courses({'Andrew Chalkley': ['jQuery Basics', 'Node.js Basics'],'Kenneth Love': ['Python Basics', 'Python Collections']})
我已经使用了** kwargs,但是为什么python无法打开字典?
在函数的定义中用a **表示的参数需要用关键字传递:
示例:
def test(**diction):
print(diction)
没有关键字的参数:
test(8)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-9-5092d794a50d> in <module> 2 print(diction) 3 ----> 4 test(8) 5 test(test_arg=9) TypeError: test() takes 0 positional arguments but 1 was given
使用任意关键字:
test(test_arg=8)
输出:
{'test_arg': 8}
编辑:
有用的链接:
使用 *args和** kwargs
**(双星/星号(和 *(星/星号(对参数做什么?
当您将dict作为参数传递时,您可以按照写作来进行:
most_courses({'Andrew Chalkley': ...
在这种情况下,most_cources
应接受"位置"参数。这就是为什么它加剧的原因:most_courses() takes 0 positional arguments but 1 was given
。
您给了它1个位置参数,而most_cources
(看起来:most_courses(**d)
(没有任何期望。
您应该做:
most_courses(**{'Andrew Chalkley': ['jQuery Basics', 'Node.js Basics'],'Kenneth Love': ['Python Basics', 'Python Collections']})
或更改方法的签名:
def most_courses(diction):
for key, value in diction.items():
print("{} {}".format(key,value))
没有理由在此处使用**
。您想通过dict并将其作为命令进行处理。只需使用标准参数。
def most_courses(diction):