TypeError: get() takes no keyword arguments

Python

Python Problem Overview


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:

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

> Following is the syntax for get() method: > > dict.get(key, default=None)

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

Python Solutions


Solution 1 - Python

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:

>>> 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

Solution 2 - Python

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

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

Solution 3 - Python

Many docs and tutorials, for instance https://www.tutorialspoint.com/python/dictionary_get.htm, erroneously specify the syntax as

dict.get(key, default = None)

instead of

dict.get(key, default)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionitsmichaelwangView Question on Stackoverflow
Solution 1 - Pythonuser2357112View Answer on Stackoverflow
Solution 2 - PythonGWWView Answer on Stackoverflow
Solution 3 - PythonBertelView Answer on Stackoverflow