Python list object has no attribute items

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

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

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 ‘items’” tells us that the list object we are handling does not have the items attribute. We will raise this error by calling the items() method on a list object. items() is a dictionary method that returns a view object containing the key-value pairs of a dictionary as a list of tuples.

The syntax for the items() method is

Let’s look at an example of calling the items() method on a dictionary. We can convert the view object into a list using the list() method:

pizza_dict = print(list(pizza_dict.items()))
[('margherita', 4), ('pepperoni', 2), ('four cheeses', 8)]

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

pizza_list = [("margherita",4), ("pepperoni",2), ("four cheeses",8)] print(list(pizza_list.items()))
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) in 1 pizza_list = [("margherita",4), ("pepperoni",2), ("four cheeses",8)] ----> 2 print(list(pizza_list.items())) AttributeError: 'list' object has no attribute 'items'

The Python interpreter throws the AttributeError because the list object does not have items() as an attribute.

Читайте также:  Java дефолтное значение boolean

Example: Getting Key-Value Pairs from a List of Dictionaries

This error can typically occur when trying to retrieve values from JSON data. A JSON will give us a list of dictionaries, not a single dictionary. Therefore, we must access each dictionary individually, not the entire list. Let’s look at an example where we have a JSON containing the inventory of a pet store. Each dictionary has three animal names as keys and the number of the animals as the values. We want to get a list of all animal numbers.

pet_store_data = [ < "dog":17, "cat":4, "rabbit":8 >, < "lizard":1, "snake":4, "dragon":2 >, < "fish":20, "frog":6, "toad":1 >] total_animal_numbers = list(pet_store_data.items()) print(f'Total number of animals in pet store: ')

We attempt to call the items() method on the list and then sum the values to get the number of animals in the pet store. Let’s run the code to see what happens:

--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) in 17 ] 18 ---> 19 total_animal_numbers = list(pet_store_data.items()) 20 21 print(f'Total number of animals in pet store: ') AttributeError: 'list' object has no attribute 'items'

We get the error because the list contains dictionaries, but the items() method is not an attribute of list objects.

Solution

To solve this error, we need to iterate over the elements in the list. The most concise and Pythonic way to do this is to use list comprehension, and list comprehension offers a shorter syntax for creating a new list based on the values of an existing list.

We will use a list comprehension to create a list containing the values of each dictionary in the pet_store_data list. Let’s look at the revised code:

pet_store_data = [ < "dog":17, "cat":4, "rabbit":8 >, < "lizard":1, "snake":4, "dragon":2 >, < "fish":20, "frog":6, "toad":1 >] total_animal_numbers = [int(v) for dct in pet_store_data for k, v in dct.items()] print(f'Total number of animals in pet store: ')

The first part of the list comprehension states to get the value from each dictionary. The second part of the list comprehension iterates over each dictionary and calls the items() method to get the values. Let’s run the code to get the correct output:

Total number of animals in pet store: 63

We see that the pet store has 63 animals in its inventory.

Summary

Congratulations on reading to the end of this tutorial! The error “AttributeError: ‘list’ object has no attribute ‘items’” occurs when you try to use the items() function to use a key to retrieve a value from a list instead of a dictionary.

The items() method is suitable for dictionaries. If you have a list of dictionaries and want to use the items() method, ensure that you iterate over each dictionary before calling the method. You can extract the values from a list of dictionaries using list comprehension.

Generally, check the object you are using before calling the items() method.

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!

Share this:

Источник

AttributeError: ‘list’ object has no attribute ‘items’ in Python – How to fix it?

AttributeError: ‘list’ object has no attribute ‘items’ in Python

If you are getting trouble with the error “AttributeError: ‘list’ object has no attribute ‘items’” in Python, keep reading our article. We will give you some methods to handle the problem.

Reason for “AttributeError: ‘list’ object has no attribute ‘items’” in Python

AttributeError is one of the most common errors in the Python programming language. The error occurs when you try to access an attribute of an object while the syntax is incorrect or the object has no attribute.

In some cases, you will get the error “AttributeError: ‘list’ object has no attribute ‘items’ in Python” when you call the attribute items to an object that belongs to the class list.

For example, we will create a list named myFib to store Fibonacci numbers. We want to take the index and the value of each element. Then we will apply the attribute items to the list to see the error.

# Function to create Fibonacci numbers def fibNumber(n): fibList = [0, 1] index = 2 if n < 2: return while index < n: fibList.append(fibList[index - 1] + fibList[index - 2]) index += 1 return fibList myFib = fibNumber(8) print(myFib.items())
AttributeError Traceback (most recent call last) in ---> 16 print(myFib.items()) AttributeError: 'list' object has no attribute 'items'

Now you understand how the error occurs. Let’s move on to discover how to solve the problem.

Solutions to this problem

Create dictionary from list

The attribute “items” is only available in the dictionary type. So you must convert the list to a dictionary to apply the attribute. We will create a dictionary named myDictFib with the key as the index of the elements by the function dict() .

# Function to create Fibonacci numbers def fibNumber(n): fibList = [0, 1] index = 2 if n < 2: return while index < n: fibList.append(fibList[index - 1] + fibList[index - 2]) index += 1 return fibList myFib = fibNumber(9) myDictFib = <>for i in range(len(myFib)): myDictFib[i] = myFib[i] print("My key - value Fibonacci numbers") print(myDictFib.items())
My key - value Fibonacci numbers dict_items([(0, 0), (1, 1), (2, 1), (3, 2), (4, 3), (5, 5), (6, 8), (7, 13), (8, 21)])

Traverse the list

You can traverse the list to see which value matches which index. In this way, we will not use the attribute items() to get key-value pairs. We will use the for loop from 0 to the length of the list and print indexes and elements’ values as our expected result.

# Function to create Fibonacci numbers def fibNumber(n): fibList = [0, 1] index = 2 if n < 2: return while index < n: fibList.append(fibList[index - 1] + fibList[index - 2]) index += 1 return fibList myFib = fibNumber(9) print("My key - value Fibonacci numbers") for i in range(len(myFib)): print(f"(:)", end=" ")
My key - value Fibonacci numbers (0:0) (1:1) (2:1) (3:2) (4:3) (5:5) (6:8) (7:13) (8:21)

Summary

We have explained to you the error “AttributeError: ‘list’ object has no attribute ‘items'” in Python and give you the solutions to fix the error. We hope you gain more knowledge after reading our article and never get the errors like that.

Maybe you are interested in similar errors:

My name is Robert Collier. I graduated in IT at HUST university. My interest is learning programming languages; my strengths are Python, C, C++, and Machine Learning/Deep Learning/NLP. I will share all the knowledge I have through my articles. Hope you like them.

Name of the university: HUST
Major: IT
Programming Languages: Python, C, C++, Machine Learning/Deep Learning/NLP

Источник

AttributeError: list object has no attribute items ( Solved )

How to Skip a Value in a List in python

AttributeError: list object has no attribute items error occurs because of accessing items() function from list object in the place of dict type of object. The items() function returns key values pair of dict object in tuple form. Since there are no key values in the list object. Also, this item() is not defined in the list Python class. Hence when we invoke items() function from the list object, It throws the AttributeError.

AttributeError: list object has no attribute items ( Solution ) –

There are multiple ways to fix this List related AttributeError but we will explore the easiest and most applicable ways in this article. Also, these solutions are scenario oriented. So while Appling any of it, please make sure to understand the context of the code.

Solution 1: Convert list to dict by adding order key –

As we know the list contains only values but the dict type object required keys and values. Hence we will use the order /location of the corresponding values in the list as the key of the dict. Here is the code for this conversion.

sample_list=['A','B','C'] sample_dict =<> for i in range(len(sample_list)): sample_dict [i]=sample_list[i] print(sample_dict.items())

list object has no attribute item fix by list to dict conversion

Solution 2: Accessing list element as dict ( if the element is dict )

This solution only works if the element of the list is a dict type. We will extract the element and then invoke items() with it. Let’s explore this with an example.

sample_list=[, ] sub=sample_list[0].items() print(sub)

list object has no attribute item fix by accessing list element as dict

Solution 3: Replacing items() without loosing purpose

Most of the time we use the items() function because we need the element of the list in tuples. This we can easily get by converting the list to a tuple.

sample_list=['A','B','C'] sample_tuple=tuple(sample_list) print(sample_tuple)

list object has no attribute item fix by simial logic replacement

Similar Articles :

AttributeError: list object has no attribute len ( Fixed )

AttributeError: list object has no attribute shape ( Solved )

Thanks
Data Science Learner Team

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

We respect your privacy and take protecting it seriously

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Источник

Оцените статью