How to Solve Python TypeError: ‘dict_items’ object is not subscriptable

by | Programming, Python, Tips

In Python, you cannot access values inside a dict_items object using indexing syntax.

A dict_items object is a view object that displays a list of a given dictionary’s key-value tuple pairs.

You can solve this error by converting the dict_items object to a list object using the built-in list() method. For example,

my_dict = {'name':'vincent', 'age':27, 'profession': 'artist'}
items = list(my_dict.items())
name = items[0]

This tutorial will detail the error and how to solve it with code examples.


TypeError: ‘dict_items’ object is not subscriptable

Let’s break up the error message to understand what the error means. TypeError occurs whenever you attempt to use an illegal operation for a specific data type. The part “dict_items object” tells us the error concerns an illegal operation for the view object returned by the dictionary items() method.

The part “is not subscriptable” tells us we cannot access an element of the dict_items object using the subscript operator, which is square brackets [].

A subscriptable object is a container for other objects and implements the __getitem__() method. Examples of subscriptable objects include strings, lists, tuples, and dictionaries.

We can check if an object implements the __getitem__() method by listing its attributes with the dir function. Let’s call the dir function and pass a dict_items object and a string object to see their attributes.

my_dict = {'fruit':'apple', 'in_stock':True, 'amount': 46}
items = my_dict.items()
print(dir(items))
['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'isdisjoint']
string = "Python"
print(dir(string))
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

If you want to check if a specific attribute belongs to an object, you can check for membership using the in operator.

my_dict = {'fruit':'apple', 'in_stock':True, 'amount': 46}
items = my_dict.items()
# Check type of object
print(type(items))
# Check membership of attribute
print('__getitem__' in dir(items))
<class 'dict_items'>
False

We can see that __getitem__ is not an attribute of the dict_items class.

string = "Python"
print(type(string))
print('__getitem__' in dir(string))
<class 'str'>
True

We can see that __getitem__ is an attribute of the string object.

Example

Let’s look at an example of trying to index a dict_items object. First, we will create the dictionary.

my_dict = {'name':'vincent', 'age':27, 'profession': 'artist'}

Then we will call the items() method on the dictionary, which returns a dictionary view object that displays a list of the dictionary’s key-value tuple pairs.

items = my_dict.items()
print(type(items))
<class 'dict_items'>

Next, we will try to access the first tuple in the dict_items object using the subscript operator [].

name = items[0]
print(name)

Let’s run the code to see what happens:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [12], in <cell line: 4>()
      2 items = my_dict.items()
      3 print(type(items))
----> 4 name = items[0]
      5 print(name)

TypeError: 'dict_items' object is not subscriptable

The error occurs because we are trying to access the first tuple using indexing, which is not possible with dict_items objects.

Solution

We can solve this error by converting the dict_items object to a list using the built-in list() method. Let’s look at the revised code:

my_dict = {'name':'vincent', 'age':27, 'profession': 'artist'}
items = list(my_dict.items())
print(type(items))
name = items[0]
print(name)

Let’s run the code to get the first key-value tuple:

<class 'list'>
('name', 'vincent')

Summary

Congratulations on reading to the end of this tutorial!

For further reading on AttributeErrors, go to the articles:

To learn more about Python for data science and machine learning, you can go to the online courses page on Python for the most comprehensive courses.

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee ✨