TypeError: dict.get() takes no keyword arguments in Python

TypeError: dict.get() takes no keyword arguments in Python

If you are facing the TypeError: dict.get() takes no keyword arguments in Python when working with the dictionary data type, keep reading our article. We will show you the root of the problem and give you some methods to deal with the problem.

The reason for the TypeError: dict.get() takes no keyword arguments in Python

The get() function is used to get the value of a dictionary by accessing the key’s name. First, take a look at the syntax of the function

Syntax:

get(key_name, value)

Parameters:

  • key_name: The name of the element to get the value.
  • value: Optional. The default value if there is no key_name in the dictionary.

As you can see, there is no keyword argument to define the default value. As a result, the error occurs because there is an unexpected keyword argument passed to the function. Look at the following example.

data = {"Name": "Cristiano Ronaldo", "Career": "Football player", "Age": "37"}
result = data.get("Nationality", default = "Portugal")

print("Cristiano Ronaldo's nationality is:",result)

Result:

Traceback (most recent call last):
   line 2, in <module>
    result = data.get("Nationality", default = "Portugal")
TypeError: dict.get() takes no keyword arguments

Solutions for this error

Use the function without the default value

Because the default value is optional, you can use the function without passing value. If the dictionary does not have the key, the result will be None. Look at the following example to see more detail.

Code:

data = {"Name": "Cristiano Ronaldo", "Career": "Football player", "Age": "37"}
 
# Get a non-exist key name without the default value
result = data.get("Nationality")
 
print("Cristiano Ronaldo's nationality is:",result)

Result:

Cristiano Ronaldo's nationality is: None

Pass the default value without keyword arguments

The function receives the default arguments directly without the keyword. So, if you want to pass the default argument, use it as a parameter, and the error will be eliminated. Look at the example below, and we pass the default value as a string.

Code:

data = {"Name": "Cristiano Ronaldo", "Career": "Football player", "Age": "37"}
 
# Pass the default value as a string
result = data.get("Nationality", "Portugal")
 
print("Cristiano Ronaldo's nationality is:",result)

Result:

Cristiano Ronaldo's nationality is: Portugal

Summary

In summary, the TypeError: dict.get() takes no keyword arguments in Python occurs because you pass a keyword argument to the get() function while it requires the value directly. There are two solutions to fix this error: do not pass the default value or pass the default value as directly as a parameter. We hope that you can handle your problem after reading our article.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *