In this article, we will discuss about the reasons of getting error ‘TypeError: ‘dict_keys’ object does not support indexing’ and how to resolve this error.
A little background,
In Python, the dictionary class provides functions keys(), values() and items() to fetch keys, values or all items (key-value pairs). But all these functions return view objects, which provides a dynamic view on the dictionary entries.
When a dictionary changes then the view reflects these changes too. We can iterate over these view objects, but we can not use indexing on these view objects. If we try to do that, then it will cause TypeError. As the dict.keys() function returns a view object, therefore we can not use the indexing on the view objects. If we try to select elements from it using indexing, then we will get this error,
TypeError: ‘dict_keys’ object does not support indexing
For example,
# Dictionary of string and int word_freq = { 'Hello' : 56, "at" : 23, 'test' : 43, 'This' : 78, 'Why' : 11 } # Fetch a view object pointing to all keys of dictionary keys = word_freq.keys() print('dict_keys view object:') print(keys) print('Try to perform indexing:') # Try to perform indexing on the key's view object will cause error first_key = keys[0] print('First Key: ', first_key)
Output:
Try to perform indexing: Traceback (most recent call last): File "temp.py", line 18, in <module> first_key = keys[0] TypeError: 'dict_keys' object does not support indexing
As we were trying to select value at index 0 from the dict_keys object, which is a view object. This view doesn’t supports the indexing, therefore, it raised a Type error i.e.
TypeError: ‘dict_keys’ object does not support indexing
How to resolve – TypeError: ‘dict_keys’ object does not support indexing
Now to avoid this error, we can convert the view object dict_keys into a list and then perform indexing on that. For example, we can cast the dict_keys object to a list object and then select element at any index from it. Let’s see the code for it,
# Dictionary of string and int word_freq = { 'Hello' : 56, "at" : 23, 'test' : 43, 'This' : 78, 'Why' : 11 } # Fetch a view object pointing to all keys of dictionary keys = list(word_freq.keys()) print('List of Keys:') print(keys) # Select 2nd element from keys list second_key = keys[1] print('Second Key: ', second_key)
Output:
List of Keys: ['Hello', 'at', 'test', 'This', 'Why'] Second Key: at
Here, we converted all the keys from dictionary to list and then selected 2nd element from the list, which is basically second key from the dictionary.
Further Learning:
- How to get first key-value pair from a Python Dictionary ?
- How to get first key in python Dictionary ?
- How to get first value in a python dictionary ?
Conclusion:
In this article we learned that view object (dict_keys) returned by dict.keys() doesn’t supports the indexing. If someone tries to select element from dict_keys using indexing, then it will raise TypeError. To avoid that error, we can cast it to list first and then select items from it using indexing.
Pandas Tutorials -Learn Data Analysis with Python
-
Pandas Tutorial Part #1 - Introduction to Data Analysis with Python
-
Pandas Tutorial Part #2 - Basics of Pandas Series
-
Pandas Tutorial Part #3 - Get & Set Series values
-
Pandas Tutorial Part #4 - Attributes & methods of Pandas Series
-
Pandas Tutorial Part #5 - Add or Remove Pandas Series elements
-
Pandas Tutorial Part #6 - Introduction to DataFrame
-
Pandas Tutorial Part #7 - DataFrame.loc[] - Select Rows / Columns by Indexing
-
Pandas Tutorial Part #8 - DataFrame.iloc[] - Select Rows / Columns by Label Names
-
Pandas Tutorial Part #9 - Filter DataFrame Rows
-
Pandas Tutorial Part #10 - Add/Remove DataFrame Rows & Columns
-
Pandas Tutorial Part #11 - DataFrame attributes & methods
-
Pandas Tutorial Part #12 - Handling Missing Data or NaN values
-
Pandas Tutorial Part #13 - Iterate over Rows & Columns of DataFrame
-
Pandas Tutorial Part #14 - Sorting DataFrame by Rows or Columns
-
Pandas Tutorial Part #15 - Merging or Concatenating DataFrames
-
Pandas Tutorial Part #16 - DataFrame GroupBy explained with examples
Are you looking to make a career in Data Science with Python?
Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.
Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.
Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.