TypeError: 'dict_items' object is not subscriptable (Python)

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: 'dict_items' object is not subscriptable (Python) #

The Python "TypeError: 'dict_items' object is not subscriptable" occurs when we try to access a dict_items object at a specific index. To solve the error, convert the dict_items object to a list, before accessing an index, e.g. list(my_dict.items())[0].

typeerror dict items object is not subscriptable

Here is an example of how the error occurs.

main.py
my_dict = {'name': 'Alice', 'age': 30} items = my_dict.items() print(type(items)) # 👉 <class 'dict_items'> # ⛔️ TypeError: 'dict_items' object is not subscriptable print(items[0])

Notice that the dict.items() method returns a dict_items object, not a list.

To solve the error, pass the dict_items object to the list constructor to convert it to a list before accessing a list item at a specific index.

main.py
my_dict = {'name': 'Alice', 'age': 30} # ✅ convert to list items = list(my_dict.items()) print(items[0]) # 👉️ ('name', 'Alice') print(items[1]) # 👉️ ('age', 30) print(items[0:2]) # 👉️ [('name', 'Alice'), ('age', 30)]

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

Since dict_items 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.

main.py
my_dict = {'name': 'Alice', 'age': 30} # ✅ convert to list items = list(my_dict.items()) try: print(items[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_items object, and converts it to a list.

The 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.

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.