Select Page

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

by | Programming, Python, Tips

In Python, the list data structure stores elements in sequential order. We can call the dictionary get() method to return the item’s value with the specified key. However, we cannot call the get() method on a list. If you try to call the get() method on a list, you will raise the error “AttributeError: ‘list’ object has no attribute ‘get’”.

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 ‘get’

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 ‘get’” tells us that the list object we are handling does not have the get attribute. We will raise this error if we call 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 get() method is

dictionary.get(keyname, value)

Parameters:

  • keyname: Required. The keyname of the item you want to retrieve the value from.
  • value: Optional. A value to return if the specified key does not exist. Default value is None.

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

pet_dict = {"dog":17, "cat":4, "rabbit":8}

num_dogs = pet_dict.get("dog")

print(num_dogs)
17

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

pet_list = [("dog", 17), ("cat",4), ("rabbit",8)]

num_dogs = pet_list.get("dog")
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-5-9748ef7d38a3> in <module>
----> 1 num_dogs = pet_list.get("dog")
AttributeError: 'list' object has no attribute 'get'

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

Example #1: Finding a Value in a List of Dictionaries

This error can typically occur when trying to retrieve values from JSON data. JSON data can give us a list of dictionaries, not a single dictionary. Therefore, we must access each dictionary individually using a for loop or the indexing operator. 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 find out how many dragons are in the store.

pet_store_data = [
{
    "dog":17, 
    "cat":4, 
    "rabbit":8
},
{
    "lizard":1, 
    "snake":4, 
    "dragon":2
},
{
    "fish":20, 
    "frog":6, 
    "toad":1
}
]

num_dragons = pet_store_data.get("dragon")

We attempt to get the number of dragons from the list of dictionaries using the get() method. Let’s run the code to see what happens:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-14-ae8701133e81> in <module>
     17 ]
     18 
---> 19 num_dragons = pet_store_data.get("dragon")
AttributeError: 'list' object has no attribute 'get'

The Python interpreter throws the error because the get() method does not belong to the list object.

Solution

To solve this error, we can iterate over the list of dictionaries and search for the key in each dictionary using the in operator. If we find the key, we will print the number to the console. Otherwise, we print that “the animal was not found“. 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
}
]

key = "dragon"

found = False

for d in json_data:

    if key in d:

        found = True

        print(f"Number of {key}s in pet store: {d[key]}")

    else:

        pass

if found == False:

        print(f"Animal: {key} not found")

We define a boolean found, which we initialise to False. If we find the key in any of the dictionaries, 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 animal was not found. Let’s run the code to see the result:

Number of dragons in pet store: 2

We find that there are two dragons in the pet store.

Let’s see what happens when we search for a whale:

pet_store_data = [
{
    "dog":17, 
    "cat":4, 
    "rabbit":8
},
{
    "lizard":1, 
    "snake":4, 
    "dragon":2
},
{
    "fish":20, 
    "frog":6, 
    "toad":1
}
]
key = "whale"

found = False

for d in json_data:

    if key in d:

        found = True

        print(f"Number of {key}s in pet store: {d[key]}")

    else:

        pass

if found == False:

        print(f"Animal: {key} not found")
Animal: whale not found

The key whale does not exist in the list of dictionaries. Therefore, we print the not found statement to the console.

For further reading on checking if a key exists in a dictionary, go to the article: How to Check if a Key Exists in a Dictionary in Python.

Example #2: Finding Value in List of Tuples

It is also common to store data in a list of tuples. If we want to retrieve a particular value within the tuples, we must iterate over the list or index the list using the indexing operator []. Let’s look at an example where some pet store data is in a list of tuples. We want to get the number of owls in the pet store. The first element of each tuple is the animal name, and the second element is the number of that animals in the store.

pet_store_data = [

('elephant', 1),

('coyote',5),

('owl', 18)

]

num_owls = pet_store_data.get("owl")

Let’s run the code to see what happens:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-18-cfea860768f6> in <module>
----> 1 num_owls = pet_store_data.get("owl")
AttributeError: 'list' object has no attribute 'get'

We get the error because the get() method does not belong to the list object pet_store_data.

Solution

To solve this error, we can use the enumerate function to iterate over the list of tuples. The enumerate() method adds a counter to an iterable and returns it as an enumerate object. We can use the counter to access each tuple in a for loop and check if the key owl is present in each tuple using the in operator. Let’s look at the revised code:

pet_store_data = [

('elephant', 1),

('coyote',5),

('owl', 18)

]

key = "owl"

found = False

for idx, tuple in enumerate(pet_store_data):

    if key in pet_store_data[idx]:

        found = True

        tup = pet_store_data[idx]

        print(f"Number of {key}s in pet store: {tup[1]}")

    else:

        pass

if found == False:

    print(f"Animal: {key}: not found")

We define a boolean found, which we initialise to False. If we find the key name in any of the tuples, 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 animal was not found. Let’s run the code to see the result:

Number of owls in pet store: 18

We find that there are 18 owls in the pet store.

Let’s see what happens when we search for a jaguar:

pet_store_data = [

('elephant', 1),

('coyote',5),

('owl', 18)

]

key = "jaguar"

found = False

for idx, tuple in enumerate(pet_store_data):

    if key in pet_store_data[idx]:

        found = True

        tup = pet_store_data[idx]

        print(f"Number of {key}s in pet store: {tup[1]}")

    else:

        pass

if found == False:

    print(f"Animal: {key} not found")
Animal: jaguar not found

The key jaguar does not exist in the list of tuples. 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 ‘get’” occurs when you try to use the get() function to use a key to retrieve a value from a list instead of a dictionary.

The get() method is suitable for dictionaries. If you have a list of dictionaries and want to use the get() method, ensure that you iterate over the items in the list of dictionaries and call the get method on each item.

Generally, check the type of object you are using before calling the get() 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!