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

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
5 min

banner

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

# Make sure to call get() on a dictionary

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

only call get method on dictionaries

If you need to check if the variable is a dictionary before calling get(), use the isinstance() method.

main.py
my_dict = {'name': 'Alice', 'age': 30} if isinstance(my_dict, dict): print(my_dict.get('name')) # ๐Ÿ‘‰๏ธ 'Alice' print(my_dict.get('age')) # ๐Ÿ‘‰๏ธ 30 else: print('The value is NOT a dictionary')

check if value is dictionary before calling get

The if block runs only if the variable stores a dictionary.

Otherwise, the else block runs.

# Reassigning the variable by mistake

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.

# Using the hasattr() method to check if the value has a get attribute

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

using hasattr method to check for get attribute

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.

# Accessing a string at a specific index

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

accessing string at specific index

Python indexes are zero-based, so the first character in a string has an index of 0, and the last character has an index of -1 or len(a_string) - 1.

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

# Getting a substring of a string with string slicing

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.

The second example starts at the character at index 6 and goes to the end of the string.

The syntax for string slicing is a_string[start:stop:step].

The start index is inclusive, whereas the stop index is exclusive (up to, but not including).

If the start index is omitted, it is considered to be 0, if the stop index is omitted, the slice goes to the end of the string.

# Working with nested dictionaries

Here is another example of how the error occurs.

main.py
my_dict = { 'a': {'name': 'Alice'}, 'b': 'Bobby' } # โ›”๏ธ AttributeError: 'str' object has no attribute 'get' my_dict['b'].get()

The dictionary has some keys that point to a nested dictionary and some keys that point to a string.

Trying to call the dict.get() method on a string caused the error.

You can use a try/except statement to handle the error in the case the key points to a string and not a nested dictionary.

main.py
my_dict = { 'a': {'name': 'Alice'}, 'b': 'Bobby' } # โ›”๏ธ AttributeError: 'str' object has no attribute 'get' try: print(my_dict['b'].get()) except AttributeError: pass

We try to call the get() method in the try statement and if an error is raised, the except block handles it.

# How to debug your code

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 will get the "AttributeError: str object has no attribute error".

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

If the error persists, follow the instructions in my AttributeError: 'str' object has no attribute 'X in Python article.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev