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.
Most of the time, we encounter this error because –
This is a prevention strategy to avoid any run time failure. Here is the code.
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)
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)
Thanks
Data Science Learner Team