Python

AttributeError: str object has no attribute get (Solved )

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 –

  1. When we expect the object type to be dict but at run time, The Interpreter found it str type.
  2. 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-

AttributeError str object has no attribute get cause

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-

str object has no attribute get 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 :

str object has no attribute get with try except

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