AttributeError: 'dict' object has no attribute 'append'

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Check out my new book

AttributeError: 'dict' object has no attribute 'append' #

The Python "AttributeError: 'dict' object has no attribute 'append'" occurs when we try to call the append() method on a dictionary. To solve the error, use bracket notation to add a key-value pair to a dict or make sure to call the append() method on a list.

attributeerror dict object has no attribute append

Here is an example of how the error occurs.

main.py
my_dict = {'name': 'Alice', 'age': 30} # ⛔️ AttributeError: 'dict' object has no attribute 'append' my_dict.append('country', 'Austria')

Dictionaries don't have an append method. Use bracket notation to add a key-value pair to a dictionary.

main.py
my_dict = {'name': 'Alice', 'age': 30} # ✅ add key-value pairs to dict my_dict['country'] = 'Austria' my_dict['prof'] = 'programmer' # {'name': 'Alice', 'age': 30, 'country': 'Austria', 'prof': 'programmer'} print(my_dict) print(my_dict['country']) # 👉️ Austria
The bracket notation syntax can be used to both access the value of a key and set or update the value for a specific key.

If you are trying to add an item to a list, you have to figure out where the variable got assigned a dictionary instead of a list.

When declaring a list, use square brackets instead of curly braces.

main.py
my_list = [] my_list.append('a') my_list.append('b') print(my_list) # 👉️ ['a', 'b']

Make sure you aren't reassigning a list to a dictionary somewhere in your code before you call append.

main.py
my_list = [] # 👇️ reassign to dictionary by mistake my_list = {'name': 'Alice'} # ⛔️ AttributeError: 'dict' object has no attribute 'append' print(my_list.append('hi'))

A good way to start debugging is to print(dir(your_object)) and see what attributes a dictionary has.

Here is an example of what printing the attributes of a dict looks like.

main.py
my_dict = {'name': 'Alice', 'age': 30} # [...'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', # 'pop', 'popitem', 'setdefault', 'update', 'values' ...] print(dir(my_dict))

If you pass a class to the dir() function, it returns a list of names of the classes' attributes, and recursively of the attributes of its bases.

If you try to access any attribute that is not in this list, you would get the "AttributeError: 'dict' object has no attribute error".

Since dict objects don't have an append() method, the error is caused.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.