python - 通过 **kwargs 获取变量,但抛出有关位置参数的错误
问题描述
尝试将字典传递给函数以将它们打印出来,但它会引发错误: most_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 不能解压字典?
解决方案
当你将你的 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))
推荐阅读
- azure - Azure Webapp - Azure .Net SDK - 设置站点 IP 限制
- firebase - 只允许登录用户读写 Firebase 数据
- apache - 试图在互联网上托管我的本地主机。我在这里想念什么?
- .net-core - .NET Core 2.2 发布因缺少 *.pdb 和 *.xml 而失败
- spring - 在 DTO 中我们可以使用 id 作为 String 还是 Long
- c# - C#中的#符号是什么
- python - 如何将 CSV 导入到两个使用 Python 相互引用的不同 SQL 表中
- vue.js - 无法安装 vuetify
- java - 如何检查一个类是否依赖 CDI 来创建实例?
- typescript - 具有客户端实用程序定义结构的基本 TypeScript NodeJS 程序,使用严格的编码规则