AttributeError: 'dict' object has no attribute 'iteritems'

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Anh Trần

AttributeError: 'dict' object has no attribute 'iteritems' #

The Python "AttributeError: 'dict' object has no attribute 'iteritems'" occurs because the iteritems() method has been removed in Python 3. To solve the error, use the items() method, e.g. my_dict.items(), to get a view of the dictionary's items.

attributeerror dict object has no attribute iteritems

Here is an example of how the error occurs.

main.py
my_dict = {'name': 'Alice', 'age': 30} # ⛔️ AttributeError: 'dict' object has no attribute 'iteritems' for key, value in my_dict.iteritems(): print(key, value)

The iteritems() method has been removed in Python 3, however we can use the items() method instead.

main.py
my_dict = {'name': 'Alice', 'age': 30} for key, value in my_dict.items(): print(key, value)

The dict.items method returns a new view of the dictionary's items ((key, value) pairs).

Note that the dict.iterkeys() and dict.itervalues() methods have also been removed.

In Python 3, we can use the dict.keys() and dict.values() methods.

main.py
my_dict = {'name': 'Alice', 'age': 30} print(my_dict.keys()) # 👉️ dict_keys(['name', 'age']) print(my_dict.values()) # 👉️ dict_values(['Alice', 30])

The dict.keys method returns a new view of the dictionary's keys.

And the dict.values method returns a new view of the dictionary's values.

A good way to start debugging is to print(dir(your_object)) and see what attributes a dictionary has.

Here is an example of what printing the attributes of a dict looks like.

main.py
my_dict = {'name': 'Alice', 'age': 30} # [...'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', # 'pop', 'popitem', 'setdefault', 'update', 'values' ...] print(dir(my_dict))

If you pass a class to the dir() function, it returns a list of names of the classes' attributes, and recursively of the attributes of its bases.

If you try to access any attribute that is not in this list, you would get the "AttributeError: 'dict' object has no attribute error".

Use the search field on my Home Page to filter through my more than 1,000 articles.