Table of Contents
ToggleWhat is a 'dict_keys' Object in Python?
Dict_keys objects are a special type of dynamic view which shows keys in a dictionary. Which means that any changes made in the dictionary will be reflected in the dict_keys view.
In simple terms ‘dict_keys’ object is a view object which provides a dynamic view of keys in the dictionary.It is a way in which we can access and iterate over the keys without creating a separate copy.
The dict_keys are associated with dictionaries in python. Dictionaries are built-in data types in Python that store data in key-value pairs. Dictionaries are mutable and unordered collections. This feature allows fast access to values based on their associated keys.
Various views in dictionary
- dict_keys: A view of the dictionary’s keys.
- dict_values: A view of the dictionary’s values.
- dict_items: A view of the dictionary’s key-value pairs.
Understanding 'dict_keys' Object is Not Subscriptable error
The error ‘dict_keys’ Object is Not Subscriptable error occur when we try to access a specific key in a dictionary using square brackets for example ‘keys_view[0]’ : The key_view is a dict_keys object and dict_keys object do not support this kind of indexing.
In simple terms, dict_keys is a view object which does not allow indexing and slicing. We can access specific keys using square brackets. If we try to do that it will raise the ‘dict_keys’ object to not be a subscriptable error.
Why 'dict_keys' Object is Not Subscriptable Error Occurs in Python
The Python 3 version’s dictionary methods like .keys(), .values(), and .items() return view objects instead of lists, leading to this error when using indexing.
Difference Between dict_keys in Python 2.x vs. 3.x
Python 2.x calling .keys() gives a list of keys which makes it subscript able. Whereas Python 3.x returns a dict_keys object which does not allow subscription.
Examples of the 'dict_keys' Object is Not Subscriptable Error
Example 1 : In the below code we are trying to access the 1st key element from the dictionary. The code fails as my_dict.keys() returns a dict_keys object which does not support indexing
my_dict = {'a': 1, 'b': 2, 'c': 3}
#Raises TypeError: 'dict_keys' object is not subscriptable first_key = my_dict.keys()[0]
output
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) in () 1 my_dict = {'a': 1, 'b': 2, 'c': 3} # Raises TypeError: 'dict_keys' object is not subscriptable
----> 2 first_key = my_dict.keys()[0] TypeError: 'dict_keys' object is not subscriptable
Solution:
Convert the dict_key object to list and then use indexing as shown in the below code.
my_dict = {'a': 1, 'b': 2, 'c': 3} # Convert dict_keys to a list to access the first key first_key = list(my_dict.keys())[0] print(first_key)
output
a
Example 2 : In the code we are trying to access the first two key elements using slicing in the dictionary but we will get a TypeError: ‘dict_keys’ object is not subscriptable as dict_keys are not subscriptable.
my_dict = {'x': 10, 'y': 20, 'z': 30} # Attempt to slice the keys view first_two_keys = my_dict.keys()[:2]
output
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) in () 1 my_dict = {'x': 10, 'y': 20, 'z': 30} 2 # Attempt to slice the keys view ----> 3 first_two_keys = my_dict.keys()[:2] TypeError: 'dict_keys' object is not subscriptable
Solution: Convert the dict_keys to list and then apply slicing as shown below.
my_dict = {'a': 1, 'b': 2, 'c': 3} first_key = list(my_dict.keys())[:2] print(first_key)
output
['a', 'b']
How to Fix the 'dict_keys' Object is Not Subscriptable Error
Converting dict_keys to a List for Subscription
first_key = list(my_dict.keys())[0]Output
a
Using Iteration to Access Dictionary Key
for key in my_dict.keys(): print(key)output
a b c
Using next(iter()) functions
my_dict = {'a': 1, 'b': 2, 'c': 3}Creating a iterator from the keys
key_iterator = iter(my_dict.keys())Looping through the iterator and printing values
for key in key_iterator: print(key)output
a b c
Is Converting dict_keys to a List Always a Good Idea?
When we convert the dict_keys object to list we are able to perform indexing but if the dictionary is large more memory will be used. If you want to see all the keys you can loop over the dict_keys object and convert the dict_keys object to list when utmost required.
How to Avoid the 'dict_keys' Object is Not Subscriptable error in Future Code
- Avoid using indexing or slicing on dict_keys, dict_values, and dict_items as they don’t allow subscription.
- We must remember that view objects are dynamic in nature. All the changes to the dictionary will reflect in the views.
- Prefer iteration over indexing in context of dictionaries in Python
- Use view objects directly when you do not need subscriptable behavior in Python dictionaries.
- Utilize dictionary view objects and iterators whenever possible to keep your code efficient and clean.
- You can also loop over the dict_keys object to get values rather than converting it to a list.
Learn the best practices to solve dict object is not callable
Conclusion
Let’s summaries approaches to solve ‘dict_keys’ Object is Not Subscriptable error
- Convert dict_keys to a list to access elements by index as dict_keys objects are not directly subscriptable.
- Use iteration to access keys without converting it to a list.
- Leverage modern alternatives like next(iter()).
Understanding the nature of dict_keys objects and how they work is important for better programming in python. By following our detailed blog you can avoid error.
You can also read our blog related to how to sort a dictionary by using key or value.