TypeError:get()不带关键字参数

时间:2021-12-29 23:22:35

I'm new at Python, and I'm trying to basically make a hash table that checks if a key points to a value in the table, and if not, initializes it to an empty array. The offending part of my code is the line:

我是Python的新手,我正在尝试基本上创建一个哈希表,检查一个键是否指向表中的值,如果不是,则将其初始化为空数组。我的代码的违规部分是这一行:

converted_comments[submission.id] = converted_comments.get(submission.id, default=0)

I get the error:

我收到错误:

TypeError: get() takes no keyword arguments

But in the documentation (and various pieces of example code), I can see that it does take a default argument:

但是在文档(以及各种示例代码)中,我可以看到它确实采用了默认参数:

https://docs.python.org/2/library/stdtypes.html#dict.get http://www.tutorialspoint.com/python/dictionary_get.htm

https://docs.python.org/2/library/stdtypes.html#dict.get http://www.tutorialspoint.com/python/dictionary_get.htm

Following is the syntax for get() method:

以下是get()方法的语法:

dict.get(key, default=None)

dict.get(key,default = None)

There's nothing about this on The Stack, so I assume it's a beginner mistake?

在堆栈上没有任何关于这个,所以我认为这是一个初学者的错误?

2 个解决方案

#1


18  

The error message says that get takes no keyword arguments but you are providing one with default=0

错误消息表明get不接受任何关键字参数,但是您提供的默认值为0

converted_comments[submission.id] = converted_comments.get(submission.id, 0)

#2


67  

Due to the way the Python C-level APIs developed, a lot of built-in functions and methods don't actually have names for their arguments. Even if the documentation calls the argument default, the function doesn't recognize the name default as referring to the optional second argument. You have to provide the argument positionally:

由于Python C级API的开发方式,许多内置函数和方法实际上没有参数的名称。即使文档调用参数default,该函数也不会将名称default识别为引用可选的第二个参数。你必须在位置上提供参数:

>>> d = {1: 2}
>>> d.get(0, default=0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: get() takes no keyword arguments
>>> d.get(0, 0)
0

#1


18  

The error message says that get takes no keyword arguments but you are providing one with default=0

错误消息表明get不接受任何关键字参数,但是您提供的默认值为0

converted_comments[submission.id] = converted_comments.get(submission.id, 0)

#2


67  

Due to the way the Python C-level APIs developed, a lot of built-in functions and methods don't actually have names for their arguments. Even if the documentation calls the argument default, the function doesn't recognize the name default as referring to the optional second argument. You have to provide the argument positionally:

由于Python C级API的开发方式,许多内置函数和方法实际上没有参数的名称。即使文档调用参数default,该函数也不会将名称default识别为引用可选的第二个参数。你必须在位置上提供参数:

>>> d = {1: 2}
>>> d.get(0, default=0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: get() takes no keyword arguments
>>> d.get(0, 0)
0