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.
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.
my_dict = {'x': 10, 'y': 20, 'z': 30}
keys = my_dict.keys()
for key in keys:
print(key)
Output:
xyz
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.