How to Fix”dict_keys’ object is not subscriptable” in Python

The error message “dict_keys’ object is not subscriptable” in Python typically occurs when try to access an element of the dictionary using the square brackets[ ] but we are attempting to do so on a dict_keys object instead of the dictionary itself.

What is “dict_keys’ object is not subscriptable” in Python?

In Python, dictionaries have several view objects such as the dict_keys, dict_values, and dict_items. These view objects provide the dynamic view of the dictionary’s entries which means that when the dictionary changes the view reflects these changes. However, dict_keys objects are not subscriptable in which means you cannot access elements in the dict_keys object using the index like you would with a list.

TypeError: ‘dict_keys’ object is not subscriptable

Reason for Error in Python

The error occurs because dict_keys objects do not support indexing. In Python, only sequences like lists, tuples, and strings can be indexed. Since dict_keys is not a sequence, attempting to use an index on it will result in a TypeError.

Reason 1: Attempting to the Index dict_keys Directly

Python
my_dict = {'a': 1, 'b': 2, 'c': 3}
keys = my_dict.keys()
print(keys[0])

Output:

TypeError: 'dict_keys' object is not subscriptable

Reason 2: Using dict_keys in the Subscriptable Context

Python
my_dict = {'x': 10, 'y': 20, 'z': 30}
keys = my_dict.keys()
for i in range(len(keys)):
    print(keys[i])

Output:

TypeError: 'dict_keys' object is not subscriptable

Fixing the Error dict_keys’ object is not subscriptable in Python

Solution 1: Convert dict_keys to a List

We can convert the dict_keys object to the list which supports indexing. By converting the dict_keys object to a list we can access the elements using the index.

Python
my_dict = {'a': 1, 'b': 2, 'c': 3}
keys = list(my_dict.keys())
print(keys[0])  # Output: 'a'

Solution 2: Iterate Directly Over dict_keys

If you don’t need to access elements by the index we can iterate over the dict_keys object directly. This approach avoids the need for the indexing entirely and works directly with dict_keys object.

Python
my_dict = {'x': 10, 'y': 20, 'z': 30}
keys = my_dict.keys()
for key in keys:
    print(key)

Output:

xyz