AttributeError: 'str' object has no attribute 'get' (Python)

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

AttributeError: 'str' object has no attribute 'get' (Python) #

The Python "AttributeError: 'str' object has no attribute 'get'" occurs when we try to call the get() method on a string instead of a dictionary. To solve the error, make sure the value is of type dict before calling the get() method on it.

attributeerror str object has no attribute get

Here is an example of how the error occurs.

main.py
my_str = 'hello world' # ⛔️ AttributeError: 'str' object has no attribute 'get' print(my_str.get('name'))

We tried to call the get() method on a string instead of a dictionary and got the error.

If you are trying to get the value of a specific key in a dictionary, make sure the value you are calling get() on is a dict.

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

Make sure the variable doesn't get reassigned to a string somewhere in your code.

main.py
my_dict = {'name': 'Alice', 'age': 30} # 👇️ reassigned to string by mistake my_dict = 'hello world' # ⛔️ AttributeError: 'str' object has no attribute 'get' print(my_dict.get('name'))

We initially set the my_dict variable to a dictionary, but later reassigned it to a string which caused the error.

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.

If you need to handle a scenario where the value is possibly not a dict, use the hasattr() method.

main.py
my_dict = {'name': 'Alice', 'age': 30} if hasattr(my_dict, 'get'): print(my_dict.get('name')) # 👉️ "Alice" else: print('Value is not a dict')

The hasattr function takes the following 2 parameters:

NameDescription
objectThe object we want to test for the existence of the attribute
nameThe name of the attribute to check for in the object

The hasattr() function returns True if the string is the name of one of the object's attributes, otherwise False is returned.

Using the hasattr function would handle the error if the get attribute doesn't exist on the object, however you still have to figure out where the variable gets assigned a string in your code.

If you are trying to access a string at a specific index, use square brackets.

main.py
my_str = 'hello world' try: print(my_str[100]) except IndexError: print('Index 100 is not present in string') # 👉️ this runs

We used a try/except statement to handle the scenario where the index we are trying to access is out of bounds.

If you need to get a substring from a string, use string slicing.

main.py
my_str = 'hello world' # 👇️ from index 0 (inclusive) to 5 (exclusive) print(my_str[0:5]) # 👉️ 'hello' # 👇️ from index 6 (inclusive) to end print(my_str[6:]) # 👉️ 'world'

The first example shows how to get the first 5 characters from a string, and the second example - from character at index 6 onwards.

A good way to start debugging is to print(dir(your_object)) and see what attributes a string has.

Here is an example of what printing the attributes of a string looks like.

main.py
my_string = 'hello world' # [ 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', # 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', # 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', # 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', # 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', # 'title', 'translate', 'upper', 'zfill'] print(dir(my_string))

If you pass a class to the dir() function, it returns a list of names of the class's attributes, and recursively of the attributes of its bases.

If you try to access any attribute that is not in this list, you would get the "AttributeError: str object has no attribute error".

Since get() is not a method implemented by strings, the error is caused.

Conclusion #

The Python "AttributeError: 'str' object has no attribute 'get'" occurs when we try to call the get() method on a string instead of a dictionary. To solve the error, make sure the value is of type dict before calling the get() method on it.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.