The AttributeError: ‘str’ object has no attribute ‘get’ mainly occurs when you try to call the get()
method on the string data type. The attribute get()
method is present in the dictionary and must be called on the dictionary data type.
In this tutorial, we will look at what exactly is AttributeError: ‘str’ object has no attribute ‘get’ and how to resolve this error with examples.
What is AttributeError: ‘str’ object has no attribute ‘get’?
If we call the get()
method on the string data type, Python will raise an AttributeError: ‘str’ object has no attribute ‘get’. The error can also happen if you have a method which returns an string instead of a dictionary.
Let us take a simple example to reproduce this error.
# Method return string instead of dict
def fetch_data():
output = "Toyota Car"
return output
data = fetch_data()
print(data.get("name"))
Output
AttributeError: 'str' object has no attribute 'get'
In the above example, we have a method fetch_data()
which returns an string instead of a dictionary.
Since we call the get()
method on the string type, we get AttributeError.
We can also check if the variable type using the type()
method, and using the dir()
method, we can also print the list of all the attributes of a given object.
# Method return string instead of dict
def fetch_data():
output = "Toyota Car"
return output
data = fetch_data()
print("The type of the object is ", type(data))
print("List of valid attributes in this object is ", dir(data))
Output
The type of the object is <class 'str'>
List of valid attributes in this object is ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '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']
How to fix AttributeError: ‘str’ object has no attribute ‘get’?
Let us see how we can resolve the error.
Solution 1 – Call the get() method on valid dictionary
We can resolve the error by calling the get()
method on the valid dictionary object instead of the string type.
The dict.get()
method returns the value of the given key. The get()
method will not throw KeyError if the key is not present; instead, we get the None
value or the default value that we pass in the get()
method.
# Method returns dict
def fetch_data():
output = {"Name": "Audi", "Release_Date": "2022", "Price": "$45000"}
return output
data = fetch_data()
# Get the car Name
print(data.get("Name"))
Output
Audi
Solution 2 – Check if the object is of type dictionary using type
Another way is to check if the object is of type dictionary; we can do that using the type()
method. This way, we can check if the object is of the correct data type before calling the get()
method.
# Method returns dict
def fetch_data():
output = {"Name": "Audi", "Release_Date": "2022", "Price": "$45000"}
return output
data = fetch_data()
# Check if the object is dict
if (type(data) == dict):
print(data.get("Name"))
softwares = "Norton, Bit Defender"
if (type(softwares) == dict):
print(softwares.get("Name"))
else:
print("The object is not dictionary and it is of type ", type(softwares))
Output
Audi
The object is not dictionary and it is of type <class 'str'>
Solution 3 – Check if the object has get attribute using hasattr
Before calling the get()
method, we can also check if the object has a certain attribute. Even if we call an external API which returns different data, using the hasattr()
method, we can check if the object has an attribute with the given name.
# Method returns dict
def fetch_data():
output = {"Name": "Audi", "Release_Date": "2022", "Price": "$45000"}
return output
data = fetch_data()
# Check if the object has get attribute
if (hasattr(data, 'get')):
print(data.get("Name"))
Output
Audi
Conclusion
The AttributeError: ‘str’ object has no attribute ‘get’ occurs when you try to call the get()
method on the string data type. The error also occurs if the calling method returns an string instead of a dictionary object.
We can resolve the error by calling the get()
method on the dictionary object instead of an string. We can check if the object is of type dictionary using the type()
method, and also, we can check if the object has a valid get attribute using hasattr()
before performing the get operation.