TypeError: 'dict_values' object is not subscriptable

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: 'dict_values' object is not subscriptable #

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

typeerror dict values object is not subscriptable

Here is an example of how the error occurs.

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

Notice that the dict.values() method returns a dict_values object, not a list.

To solve the error, pass the dict_values 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 values = list(my_dict.values()) print(values[0]) # 👉️ "Alice" print(values[1]) # 👉️ 30 print(values[0:2]) # 👉️ ['Alice', 30]

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

Since dict_values 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 values = list(my_dict.values()) try: print(values[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_values 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.

Conclusion #

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

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.