Select Page

How to Solve Python AttributeError: ‘dict’ object has no attribute ‘append’

by | Programming, Python, Tips

In Python, a dictionary stores data values in key-value pairs. If you use the append() method to add new values to a dictionary, you will raise the AttributeError: ‘dict’ object has no attribute append. The append() method belongs to the list data type and not the dictionary data type.

You can solve this error by adding a value to a key using the subscript operator []. You can also use the update method to add key-value pairs to a dictionary. Otherwise, you can use a list instead of a dictionary to store data values and call the append method on the list object.

This tutorial will go through the error in detail and solve it with the help of code examples.


AttributeError: ‘dict’ object has no attribute ‘append’

AttributeError occurs in a Python program when we try to access an attribute (method or property) that does not exist for a particular object. The part “‘dict’ object has no attribute ‘append’” tells us that the dictionary object we are handling does not have the append attribute. The append() method belongs to the list data type. The syntax of the append method is as follows:

list.append(element)

Parameter:

  • element: Required. An element of any type (string, number, object)

Let’s see what happens when we call the append method on a list:

fruits = ["banana", "pineapple", "mango", "lychee"]
fruits.append("guava")
print(fruits)
['banana', 'pineapple', 'mango', 'lychee', 'guava']

Next, let’s see what happens when you try to call the append method on a dictionary:

fruits = {"banana":1, "pineapple":1, "manga":1, "lychee":1}
fruits.append("guava")
print(fruits)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-2-375f900f5da2> in <module>
      1 fruits = {"banana":1, "pineapple":1, "manga":1, "lychee":1}
----> 2 fruits.append("guava")
      3 print(fruits)
AttributeError: 'dict' object has no attribute 'append'

The Python interpreter raises the error because the append() method does not belong to the dictionary data type.

Example #1: Adding Items to a Dictionary

Let’s look at an example where we try to read a csv file containing a pizza menu into a dictionary. Each item in the dictionary will have a pizza name as a key and the price as a value. The csv file pizza_prices.csv looks like this:

margherita,7.99
pepperoni,8.99
four cheese,10.99
chicken and sweetcorn,9.99                            

We will read the CSV file using the CSV library and iterate over the rows in the file using a for loop. Then we will attempt to append each row to the dictionary.

import csv 
pizza_dict = {}
with open('pizza_prices.csv', 'r') as f:
    csvf = csv.reader(f)
    for row in csvf:
        pizza_dict.append(row)
print(f'Pizza menu: {pizza_dict}') 

Let’s run the code to see what happens:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-2-f8fac7a9aeab> in <module>
      7         key = row[0]
      8         value = row[0]
----> 9         pizza_dict.append(row)
     10 
     11 print(f'Pizza menu: {pizza_dict}')
AttributeError: 'dict' object has no attribute 'append'

We throw the AttributeError because the append() method is not an attribute of the dictionary data type.

Solution #1: Use the Subscript Operator

We can use the subscript operator [] to add a value to a key in a dictionary object. The syntax for the subscript operator is:

dictionary[key] = value

Let’s look at the revised code:

import csv 
pizza_dict = {}
with open('pizza_prices.csv', 'r') as f:
    csvf = csv.reader(f)
    for row in csvf:
        key = row[0]
        val = row[1]
        pizza_dict[key] = val
print(f'Pizza menu: {pizza_dict}') 

We split each row into a key and a value. Then we use the subscript operator to add each value (pizza price) to its corresponding key (pizza name). Let’s run the code to see the result:

Pizza menu: {'margherita': '7.99', 'pepperoni': '8.99', 'four cheese': '10.99', 'chicken and sweetcorn': '9.99'}

We successfully read the lines in the CSV file into a dictionary.

Solution #2: Use the Dictionary update() Method

We can use the update() to add a dictionary or an iterable object with key-value pairs into a dictionary. The syntax for the update() method is:

dictionary.update(iterable)

Parameters:

  • iterable. Required. A dictionary or iterable object with key value pairs to insert into the dictionary.

Let’s look at the use of the update() method to add key-value pairs to the pizza_dict:

import csv 
pizza_dict = {}
with open('pizza_prices.csv', 'r') as f:
    csvf = csv.reader(f)
    for row in csvf:
        key = row[0]
        val = row[1]
        pizza_dict.update({key:val})
print(f'Pizza menu: {pizza_dict}') 

In the above code, we pass the key-value pair inside a dictionary using curly brackets to the update method. Let’s run the code to see the result:

Pizza menu: {'margherita': '7.99', 'pepperoni': '8.99', 'four cheese': '10.99', 'chicken and sweetcorn': '9.99'}

We successfully read the lines in the CSV file into a dictionary using the update() method.

Solution #3: Use a List Instead of a Dictionary

Alternatively, we could use a list instead of a dictionary and then call the append() method. We can define an empty list using square brackets []. Let’s look at the revised code:

import csv 
pizza_list = []
with open('pizza_prices.csv', 'r') as f:
    csvf = csv.reader(f)
    for row in csvf:
        pizza = tuple(row)
        pizza_list.append(pizza)
        
print(f'Pizza menu: {pizza_list}') 

Using the built-in tuple () method, we convert each row into a tuple using the built-in tuple() method. Then we append each tuple to the list object. Let’s run the code to see the result:

Pizza menu: [('margherita', '7.99'), ('pepperoni', '8.99'), ('four cheese', '10.99'), ('chicken and sweetcorn', '9.99')]

We successfully read the lines in the CSV file into a list.

Example #2: Appending Values to Lists in Dictionaries

In this example, we have a dictionary where the keys are strings representing vegetable names, and the values are lists representing the monthly stock of each vegetable. We want to append the stock for the two vegetables for the fifth recorded month. Let’s look at the code:

vegetable_stock = { 
"asparagus": [10, 20, 13, 40], 
"spinach": [40, 50, 20, 30]
}
vegetable_stock.append(20, 50)

Let’s run the code to see what happens:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-8-694eff1ddb54> in <module>
      3 "spinach": [40, 50, 20, 30]
      4 }
----> 5 vegetable_stock.append(20, 50)
AttributeError: 'dict' object has no attribute 'append'

The error occurs because we are calling the append() method on the dictionary even though the values of the dictionaries are lists.

Solution

To solve this error, we need to access the dictionary’s values using their keys. Once we pass the key to the dictionary using the subscript operator, we will retrieve the list we can append. Let’s look at the revised code:

vegetable_stock = { 
"asparagus": [10, 20, 13, 40], 
"spinach": [40, 50, 20, 30]
}
vegetable_stock["asparagus"].append(20)
vegetable_stock["spinach"].append(50)
print(f'Updated vegetable stock: {vegetable_stock}')

To solve this error, we need to access the dictionary’s values using their keys. Once we pass the key to the dictionary using the subscript operator, we will retrieve the list and call append(). Let’s run the code to get the result:

Updated vegetable stock: {'asparagus': [10, 20, 13, 40, 20], 'spinach': [40, 50, 20, 30, 50]}

We successfully updated both values in the dictionary.

Summary

Congratulations on reading to the end of this tutorial! The AttributeError: ‘dict’ object has no attribute ‘append’ occurs when you call the append() method on a dictionary. This error typically occurs when you add an item to a dictionary or update a list inside a dictionary.

To solve this error, you can either use the subscript operator [] to add a value to a key, use the update() method to replace a previous value, or use a list instead of a dictionary. If you have a list as a value in a dictionary and you want to update it, you can access the list directly by passing the key for that list to the dictionary.

For further reading on AttributeErrors involving the list object, go to the articles:

To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.

Have fun and happy researching!