Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Alex Gruber
The Python "TypeError: 'dict_keys' object is not subscriptable" occurs when we
try to access a dict_keys object at a specific index. To solve the error,
convert the dict_keys
object to a list, before accessing an index, e.g.
list(my_dict.keys())[0]
.
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'> # ⛔️ TypeError: 'dict_keys' object is not subscriptable print(keys[0])
Notice that the dict.keys()
method returns a dict_keys
object, not a list
.
To solve the error, pass the dict_keys
object to the list
constructor to
convert it to a list before accessing a list item at a specific index.
my_dict = {'name': 'Alice', 'age': 30} # ✅ convert to list keys = list(my_dict.keys()) print(keys[0]) # 👉️ "name" print(keys[1]) # 👉️ "age" print(keys[0:2]) # 👉️ ['name', 'age']
The dict.keys method returns a new view of the dictionary's keys.
dict_keys
objects are not subscriptable, we can't access them at a specific index.Note that if you try to access a list index that is out of bounds, you would get
an error. You can use a try/except
statement if you need to handle that.
my_dict = {'name': 'Alice', 'age': 30} keys = list(my_dict.keys()) try: print(keys[100]) except IndexError: print('index out of bounds') # 👉️ this runs
The example catches the IndexError
that is thrown if the index is out of
bounds.
The list constructor
takes an iterable, such as a dict_keys
object, and converts it to a list.
list
constructor builds a list whose items are the same and in the same order as the iterable's items.The list
constructor takes an iterable that may be a sequence, a container
that supports iteration, or an iterator object.