Borislav Hadzhiev
Wed Apr 20 2022·1 min read
Photo by Chris Ghinda
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()
.
Here is an example of how the error occurs.
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.
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.
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).
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')]