How to Solve Python AttributeError: ‘list’ object has no attribute ‘values’

by | Programming, Python, Tips

In Python, the list data structure stores elements in sequential order. We can use the dictionary values() method to return a view object containing the dictionary’s values as a list.

However, we cannot apply the values() method to a list. If you try to use the values() method on a list, you will raise the error “AttributeError: ‘list’ object has no attribute ‘values’”.

This tutorial will go into detail on the error definition. We will go through an example that causes the error and how to solve it.


AttributeError: ‘list’ object has no attribute ‘values’

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 “‘list’ object has no attribute ‘values’” tells us that the list object we are handling does not have the get attribute. We will raise this error by calling the get() method on a list object. get() is a dictionary method that returns the value of an item with the specified key.

The syntax for the values() method is:

dictionary.values()

Let’s look at an example of calling the values() method on a dictionary:

pizza_dict = {"margherita":4, "pepperoni":2, "four cheeses":8}
print(list(pizza_dict.values()))
[4, 2, 8]

Now we will see what happens if we try to use the values() method on a list:

pizza_list = [("margherita",4), ("pepperoni",2), ("four cheeses",8)]
print(list(pizza_list.values()))
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-3-7ac2157a441a> in <module>
      1 pizza_list = [("margherita",4), ("pepperoni",2), ("four cheeses",8)]
----> 2 print(list(pizza_list.values()))
AttributeError: 'list' object has no attribute 'values'

The Python interpreter throws the Attribute error because the list object does not have values() as an attribute.

Example: Read Values from CSV File

Let’s look at an example where we read a CSV into a dictionary using the CSV module. First, we will define a CSV file containing a pizza menu with the pizza names, prices and whether the pizza is vegetarian or not. The file looks like this:

margherita, 7.99, vegetarian
pepperoni, 8.99, non-vegetarian
four cheeses, 9.99, vegetarian
chicken and sweetcorn, 9.99, non-vegetarian

Let’s read the file and define a dictionary with the pizza names as keys and the price and vegetarian flag in a list as values. We want to find a specific pizza in the dictionary, unpack the list of values for that pizza, and print it to the console. Let’s look at the code:

import csv
pizza_dict = {}
with open('pizza_menu.csv') as csvf:
   csv_file = csv.reader(csvf)
   for row in csv_file:
       pizza_dict[row[0]] = row[1:]
key = "margherita"
found = False
for row in pizza_dict:
    if row == key:
        found = True
        price, is_vegetarian = pizza_dict[row].values()
        print(f'The pizza {key} costs {price}. Is Vegetarian? {is_vegetarian}')
    else:
        pass
if found == False:
    print(f'The pizza {key} not found on menu')

We define a boolean found, which we initialise to False. If we find the key name in the dictionary, we set the boolean to True. Otherwise, it stays as False. Once we exit the loop, if the found variable remains false, we print that the pizza was not found. Let’s run the code to see the result:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-10-2723e6269722> in <module>
     12 for row in pizza_dict:
     13     if row == key:
---> 14         price, is_vegetarian = pizza_dict[row].values()
     15         print(f'The pizza {key} costs {price}. Is Vegetarian? {is_vegetarian}')
     16 
AttributeError: 'list' object has no attribute 'values'

The Python interpreter throws the error because we called values on pizza_dict[row], which is a list. The values() method does not belong to the list object.

Solution

We do not need to call the values() if we pass a key to the dictionary. We will get the values as a list, and we can unpack the list directly as follows:

import csv
pizza_dict = {}
with open('pizza_menu.csv') as csvf:
    csv_file = csv.reader(csvf)
    for row in csv_file:
        pizza_dict[row[0]] = row[1:]
key = "margherita"
found=False
for row in pizza_dict:
    if row == key:
        found=True
        price, is_vegetarian = pizza_dict[row]
        print(f'The pizza {key} costs {price}. Is Vegetarian? {is_vegetarian}')
    else:
        pass
if found == False:
    print(f'The pizza {key} not found on menu')

Let’s run the code to see the result:

The pizza margherita costs  7.99. Is Vegetarian?  True

Let’s see what happens when we search for a ham and pineapple pizza:

import csv
pizza_dict = {}
with open('pizza_menu.csv') as csvf:
    csv_file = csv.reader(csvf)
    for row in csv_file:
        pizza_dict[row[0]] = row[1:]
key = "ham and pineapple"
found=False
for row in pizza_dict:
    if row == key:
        found=True
        price, is_vegetarian = pizza_dict[row]
        print(f'The pizza {key} costs {price}. Is Vegetarian? {is_vegetarian}')
    else:
        pass
if found == False:
    print(f'The pizza {key} not found on menu')
The pizza ham and pineapple not found on menu

The key “ham and pineapple” does not exist in the dictionary, and therefore, we print the not found statement to the console.

Summary

Congratulations on reading to the end of this tutorial! The error “AttributeError: ‘list’ object has no attribute ‘values’” occurs when you try to use the values() method on a list.

The values() method is suitable for dictionaries. You can get the values of a dictionary using the required key.

If you have a list and want to find a specific element, you can use the in operator.

Generally, check the type of object you are using before calling the get() method.

For further reading on AttributeErrors, 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!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee