AttributeError: str object has no attribute get error occurs because of invoking get() function/ attribute from str type object. Actually, this get() attribute is available in dict type object to values of a corresponding key.
AttributeError: str object has no attribute get (Root Cause ) –
Anyways, this error generally occurs in two main situations –
- When we expect the object type to be dict but at run time, The Interpreter found it str type.
- The intent is to extract the individual element from the str but somehow used incorrect syntax.
Since the Root cause is completly in two different directions. So we will resolve this error differently as well.
AttributeError: str object has no attribute get (Solution ) –
Let’s explore the error’s solution.
Solution 1: Using Index to retrieve value –
When we want to extract the value of str element at a specific index and we used get() function for this. Here we get this issue.
replication-
Here in the above code in sample_str when we use get() function to retrieve the element at the second index we get this error.
Fix-
Solution 2: Runtime object check –
This is very common, In some cases, we took some input from config file or user. There we expect that the type of the input will be in key, value format which means dict type of object. But on the real ground or actual flow, The underline object remains str type which triggers this AttibuteError.
The best fix here is to apply to try and except the block and check the object type. Let’s understand with the below example.
obj="Input from usr"
try:
print(obj.get(2))
except:
print(" Invalid Input type")
print(type(obj))
Output :
To simply apply try and except can avoid multiple run time errors.
Bonus Article :
What is AttributeError in Python ? Complete Overview
Thanks
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.