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

by | Programming, Python, Tips

This error occurs when you try to call the keys() method on a list as if it were a Python dictionary. You can solve this error by calling the keys() method on a dict instead of a list. If you have a list of dictionaries, you can access each dictionary using the subscript operator [] and the specific index, then call the keys() method on the dictionary directly. For example,

list_of_dict = [

{'name':'biff', 'age': 18},

{'name':'jill', 'age': 87}

]

keys = list(list_of_dict[0].keys())

This tutorial will go through the error in detail with code examples.


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

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

keys() is a Python dictionary method that returns a view object containing the keys of the specified dictionary as a list.

Example #1

Let’s look at an example of using the keys() method. First, we will define a list of dictionaries:

student_list = [

{'name': 'george', 'age':18, 'subject':'chemistry', 'grade':'A'},

{'name': 'bill', 'age':17, 'subject':'physics', 'grade':'B'},

{'name': 'xavier', 'age':18, 'subject':'biology', 'grade':'C'},

{'name': 'gemma', 'age':17, 'subject':'mathematics', 'grade':'B'}

]

Next, we will define a function which converts the list of dictionaries into a nested dictionary:

def get_nested_dict(my_list):

    new_dict = {}

    for i in my_list.keys():

        if i == 'name':

            continue

        new_dict[mylist['name']][i] = my_list[i]

    return new_dict

In the above code, we are attempting to use the keys() method to iterate over the different keys in student_list to create a nested dictionary.

Let’s try to pass the list containing the student details to the get_nested_dict function and run the code to see what happens:

get_nested_dict(student_list)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [8], in <cell line: 1>()
----> 1 get_nested_dict(student_list)

Input In [7], in get_nested_dict(my_list)
      1 def get_nested_dict(my_list):
      2     new_dict = {}
----> 3     for i in my_list.keys():
      4         if i == 'name':
      5             continue

AttributeError: 'list' object has no attribute 'keys'

The error occurs because student_list is a list object, not a dict. We can check what attributes the list data type has by using the dir() method. For example,

dir(list)
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__gt__',
 '__hash__',
 '__iadd__',
 '__imul__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__reversed__',
 '__rmul__',
 '__setattr__',
 '__setitem__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'append',
 'clear',
 'copy',
 'count',
 'extend',
 'index',
 'insert',
 'pop',
 'remove',
 'reverse',
 'sort']

When we call the dir() method it returns a list containing the attributes of the specified objects, without the values.

We can check for membership of a specific attribute using the in operator. If the in operator evaluates to True then the attribute exists in the list returned by dir(). If the in operator evaluates to values then the attribute does not exist in the list returned by dir().

print('keys' in dir(list))
False

The membership check returns False, verifying that keys() is not an attribute of the list data type.

Solution

We can solve the error by iterating over the dictionaries in the list using a for loop. Let’s look at the revised code:

def get_nested_dict(my_list):

    new_dict = {}

    for dic in my_list:

        new_dict[dic['name']] = {}

        for k in dic.keys():

            if k == 'name':

                continue

            new_dict[dic['name']][k] = dic[k]

            print(dic[k])

    return new_dict

In the above code we iterate over each dictionary in the list and then iterate over the keys in each dictionary. Inside the keys loop we create a nested dictionary where the key is the name and the value is dictionary containing the remaining key-value pairs.

Let’s pass the student_list dictionary to the function to get the nested dictionary:

my_dict = get_nested_dict(student_list)

We can get the information for a particular student by using the name key in the nested dictionary. Let’s get the information for the student george:

my_dict['george']
{'age': 18, 'subject': 'chemistry', 'grade': 'A'}

We successfully retrieved the information from the nested dictionary.

Example #2

Let’s look at another example of using the keys() method. We will use the same list of dictionaries as in the previous example.

student_list = [

{'name': 'george', 'age':18, 'subject':'chemistry', 'grade':'A'},

{'name': 'bill', 'age':17, 'subject':'physics', 'grade':'B'},

{'name': 'xavier', 'age':18, 'subject':'biology', 'grade':'C'},

{'name': 'gemma', 'age':17, 'subject':'mathematics', 'grade':'B'}

]

Next, we will try to call the keys() method on the list to get the keys of the dictionaries.

print(list(student_list.keys()))

Let’s run the code to see what happens:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [13], in <cell line: 1>()
----> 1 print(list(student_list.keys()))

AttributeError: 'list' object has no attribute 'keys'

The error occurs because student_list is a list object not a dict object. List objects do not have keys() as an attribute.

Solution

We can solve this error by using indexing to retrieve a single dictionary from the list. We can then call the keys() method on that dictionary. We can index a list using the subscript operator, [].

We will use the dictionary at the 0 index as follows:

print(list(student_list[0].keys()))

Let’s run the code to see the result:

['name', 'age', 'subject', 'grade']

We can use the filter function to find all dictionaries in the list that match a specific condition. Let’s use the filter function to find the students that studied mathematics:

 math_student = list(filter(lambda student: student.get('subject')=='mathematics', student_list)

Let’s run the code to see the result:

[{'name': 'gemma', 'age': 17, 'subject': 'mathematics', 'grade': 'B'}]

We successfully found the information student gemma, who studied mathematics.

Summary

Congratulations on reading to the end of this tutorial!

For further reading on AttributeErrors, go to the article:

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

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 ✨