Attributeerror: dict object has no attribute ‘iteritems’ error occurs while using dict.iteritems() attribute with Python 3 since dict.iteritems() is removed in python 3. In the place of iteritems() use dict.items() . The iteritems() will work fine with python 2. Anyways to get the full depth of the error, We will first replicate this error and then we will fix the error.
What does iteritems do ?
The iteriterms attributes allows you to items present in the dictionary. Suppose you have a dictionary and wants to get the key values then you will use the iteritems on that dictionary. It works similar to the for loop. You will get key and its value on each iteration.
Attributeerror: dict object has no attribute ‘iteritems’ ( root cause ) –
As we have explained this error is due to python version syntax incompatibility. To replicate the same issue we will use the python 3 interpreter. Here is the code for the same.
Attributeerror: dict object has no attribute ‘iteritems’ ( Solution ) –
There are two approaches to fix this problem. Let’s understand them section-wise.
Solution 1: Replacing iteritems() with dict.items() –
In python 3 we can achieve the same iterating object with dict. items(). To have a practical example, we will use the small syntax in the above example.
Solution 2: Downgrade the python version ( Not Recommended ) –
Since the root cause of this code incompatibility is the python version and syntax depreciation. If we downgrade the version of python from 3 to 2. x. This will remove the incompatibility. But we do not recommend the same because it may fix this error but can create multiple incompatibilities. You should try this method if you are sure your entire code is in Python 2. x only.
Solution 3: Using Incompatibilty Handler packages (Six or Future.utils ) –
Since this incompatibility is a major concern for old python projects. To avoid the workaround, we have some third-party libraries. If we install them and import then we can get rid of this type of error. The Python package six and future.utils are mainly for the same.
End Notes :
There are multiple similar errors:
Attributeerror: dict object has no attribute ‘iterkeys’
Attributeerror: dict object has no attribute ‘itervalues’
Actually, all three attributes are now in the below form syntax-
dict.iterkeys -> dict.iterkeys
dict.itervalues -> dict.itervalues
If you want to understand more AttributeErrors, Read this well-articulated article.
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.