AttributeError: dict_keys object has no attribute 'remove'

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

AttributeError: dict_keys object has no attribute 'remove' #

The Python "AttributeError: 'dict_keys' object has no attribute 'remove'" occurs when we try to call the remove() method on a view of the dictionary's keys. To solve the error, pass the view to the list() constructor before calling remove().

attributeerror dict keys object has no attribute remove

Here is an example of how the error occurs.

main.py
my_dict = {'name': 'Alice', 'age': 30} keys = my_dict.keys() print(type(keys)) # 👉️ <class 'dict_keys'> # ⛔️ AttributeError: 'dict_keys' object has no attribute 'remove' keys.remove('age')

The dict.keys method returns a new view of the dictionary's keys.

To get a list, we have to pass the view to the list() constructor.

main.py
my_dict = {'name': 'Alice', 'age': 30} keys = list(my_dict.keys()) print(type(keys)) # 👉️ <class 'list'> keys.remove('age') print(keys) # 👉️ ['name']

We converted the view object into a list by passing it to the list() constructor.

The list.remove() method removes the first item from the list whose value is equal to the passed in argument.

The method raises a ValueError if there is no such item.

The remove() method mutates the original list and returns None.

Note that the dict.values() and dict.items() methods also return view objects.

The dict.values method returns a new view of the dictionary's values.

main.py
my_dict = {'id': 1, 'name': 'Alice'} print(my_dict.values()) # 👉️ dict_values([1, 'Alice']) list_of_values = list(my_dict.values()) print(list_of_values) # 👉️ [1, 'Alice']

The dict.items method returns a new view of the dictionary's items ((key, value) pairs).

main.py
my_dict = {'id': 1, 'name': 'Alice'} print(my_dict.items()) # 👉️ dict_items([('id', 1), ('name', 'Alice')]) list_of_items = list(my_dict.items()) print(list_of_items) # 👉️ [('id', 1), ('name', 'Alice')]

Conclusion #

The Python "AttributeError: 'dict_keys' object has no attribute 'remove'" occurs when we try to call the remove() method on a view of the dictionary's keys. To solve the error, pass the view to the list() constructor before calling remove().

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.