Last updated: Apr 8, 2024
Reading timeยท5 min
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.
Here is an example of how the error occurs.
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.
my_dict = {'name': 'Alice', 'age': 30} print(my_dict.get('name')) # ๐๏ธ 'Alice' print(my_dict.get('age')) # ๐๏ธ 30
If you need to check if the variable is a dictionary before calling get()
, use
the isinstance()
method.
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')
The if
block runs only if the variable stores a dictionary.
Otherwise, the else
block runs.
Make sure the variable doesn't get reassigned to a string somewhere in your code.
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:
Name | Description |
---|---|
key | The key for which to return the value |
default | The 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
.
hasattr()
method to check if the value has a get
attributeIf you need to handle a scenario where the value is possibly not a dict
, use
the hasattr()
method.
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:
Name | Description |
---|---|
object | The object we want to test for the existence of the attribute |
name | The 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.
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.
my_str = 'hello world' try: print(my_str[100]) except IndexError: print('Index 100 is not present in string') # ๐๏ธ this runs
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.
If you need to get a substring from a string, use string slicing.
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.
Here is another example of how the error occurs.
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.
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.
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.
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.
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.
You can learn more about the related topics by checking out the following tutorials: