Borislav Hadzhiev
Wed Apr 20 2022·3 min read
Photo by Peter Thomas
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
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
.
If 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
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, 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.
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 classes' attributes, and recursively of the attributes of its bases.
Since get()
is not a method implemented by strings, the error is caused.