首页 > 解决方案 > 通过 **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 不能解压字典?

标签: 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))

推荐阅读