How to Fix AttributeError: 'Dict' Object Has No Attribute 'Append' in Python

Shihab Sikder Feb 02, 2024
  1. the AttributeError: 'dict' object has no attribute 'append' in Python
  2. Handle the AttributeError: 'dict' object has no attribute 'append' in Python
How to Fix AttributeError: 'Dict' Object Has No Attribute 'Append' in Python

dict is a data structure that uses the hash map, which differs from the list. It doesn’t have the append() function, while the list data structure has the append() function.

the AttributeError: 'dict' object has no attribute 'append' in Python

Dictionary can hold a list inside it. We can’t directly append the dictionary, but if there’s a list inside the dictionary, we can easily append that.

For example,

>>> dict = {}
>>> dict["numbers"]=[1,2,3]
>>> dict["numbers"]
[1, 2, 3]
>>> dict["numbers"].append(4)
>>> dict["numbers"]
[1, 2, 3, 4]

Here, the numbers key has a list as the value. We can append this, but let’s say we want to append the dict.

It will show the following error:

>>> dict = {}
>>> dict["numbers"]=[1,2,3]
>>> dict.append(12)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'append'

Handle the AttributeError: 'dict' object has no attribute 'append' in Python

The value can be anything: a tuple, list, string, or even another dictionary. To prevent this error, we can check the type of value for a particular key inside a dictionary.

For this, we need to evaluate whether the key exists inside the dictionary or not.

Let’s see the example below:

dict = {}

dict["nums"] = [1, 2, 3]
dict["tuple"] = (1, 2, 3)
dict["name"] = "Alex"

if dict.get("name", False):
    if type(dict["name"]) is list:
        dict["name"].append("Another Name")
    else:
        print("The data type is not a list")
else:
    print("This key isn't valid")

Output:

The data type is not a list

It could give us the error like the previous one, but we are evaluating the dictionary’s key here. Then we check if the value is a list or not.

After that, we are appending the list.

To know more about the Python dictionary, read this blog.

Shihab Sikder avatar Shihab Sikder avatar

I'm Shihab Sikder, a professional Backend Developer with experience in problem-solving and content writing. Building secure, scalable, and reliable backend architecture is my motive. I'm working with two companies as a part-time backend engineer.

LinkedIn Website

Related Article - Python Error