Attributeerror: dict object has no attribute append ( Solved )

Attributeerror_ dict object has no attribute append ( Solved )

AttributeError: dict object has no attribute append occurs if we invoke append attribute from dict type object however there is no append attribute defined under dict class. This append() attribute is present in the list type object.

Attributeerror: dict object has no attribute append ( Root Cause ) –

Most of the time, we encounter this error because –

  1. At Runtime, the code expects another data type like list, etc but some show in the code flow, The program actually gets dict as an object type. If there we do not use the try-except block, we encounter this error.
  2. The intent is to add the element at the last and keep the object the same but due to confusion in syntax, we accidentally use append() function which does not exist. It ends up at this attributerror.
dict has no attribute append
dict has no attribute append

AttributeError: dict object has no attribute append ( Solution ) –

Solution 1:  Using Runtime try-except –

This is a prevention strategy to avoid any run time failure. Here is the code.

dict has no attribute append solution using try and except
dict has no attribute append solution using try and except

 

Solution 2: Use subscription and assignment –

Just in the similar line of the above solution, we can use subscript and assignment in place of append. This will fulfill the outcome. The only difference is there we runtime first tries to use append and when the interpreter raises the exception we use subscript and assignment but here we will first check the object type and intentionally use append if the object is list type and subscript and assignment when it is dict.

obj={1:'A',2:'B'}
if(type(obj)==list):
  obj.append("C")
  print(obj)
else:
  print("This is dict type")
  obj[3]="C"
  print(obj)
dict has no attribute append solution using subscript and assignment
dict has no attribute append solution using subscript and assignment

Solution 3: extract the list and append ( Specific case )-

In case any values in the dict object are list type. Then we have to first extract and then use append(). Let’s take and example and understand-

obj={1:'A',2: ['B']}
temp_list = obj.get(2)
temp_list.append("C")
obj[2]=temp_list
print(obj)
dict has no attribute append solution if the value is of list type
dict has no attribute append solution if the value is of list type

Similar Error –

Attributeerror: dict object has no attribute has_key ( Solution )

 

Thanks

Data Science Learner Team

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

 
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner