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

avatar

Borislav Hadzhiev

Wed Apr 20 20221 min read

banner

Photo by Sam Kuhn

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

The Python "TypeError: dict.get() takes no keyword arguments" occurs when we pass keyword arguments to the dict.get() method. To solve the error, only pass positional arguments to dict.get(), e.g. my_dict.get('my_key', 'default').

typeerror dict get takes no keyword arguments

Here is an example of how the error occurs.

main.py
my_dict = {'name': 'Alice', 'age': 30} # ⛔️ TypeError: dict.get() takes no keyword arguments result = my_dict.get('name', default='')

The error was caused because we passed a keyword argument to the dict.get() method.

The dict.get() method takes only positional arguments.

main.py
my_dict = {'name': 'Alice', 'age': 30} print(my_dict.get('name', '')) # 👉️ "Alice" print(my_dict.get('another', 'default')) # 👉️ 'default'

The dict.get method returns the value for the given key if the key is in the dictionary, otherwise a default value is returned.

The method takes the following 2 parameters:

NameDescription
keyThe key for which to return the value
defaultThe default value to be returned if the provided key is not present in the dictionary (optional)
If a value for the default parameter is not provided, it defaults to None, so the get() method never raises a KeyError.

Both of the arguments the dict.get() method takes are positional.

You can't pass a keyword argument to the method.

If the provided key exists in the dict object, its value is returned, otherwise the get() method returns the supplied default value or None if one wasn't provided when calling dict.get().

Use the search field on my Home Page to filter through my more than 1,000 articles.