How to Fix the error ‘dict’ object has no attribute ‘iteritems’ in Python 3?

[toc]

Reason Behind: ‘dict’ object has no attribute ‘iteritems’

Many changes are done from Python 2 to Python 3. One such change is in the attributes of the dictionary class. The dict attribute, i.e., dict.iteritems() has been removed and a new method has been added to achieve the same result. 

First, let us try to understand why this attribute was removed. Earlier versions of Python 2 had the dict.items() method that returned a list of tuples in the dictionary. Consider the following example:

# Exceuting the code in Python 2 

a={'1':"first", '2':"second" , '3':"third" }
print(a.items())

# [('1', 'first'), ('3', 'third'), ('2', 'second')]

Discussion: We can see that the output is a list of tuples and every tuple consits of a key-value pair of a dictionary as its elements. Here we can see, all the contents of the dictionary were copied to the list. Evidently, this consumed a lot of memory. So, in the later versions of Python 2, dict.iteritems() method was created to overcome the memory issue. This method returned an iterable object.

Refer to the below example:

# Exceuting the code in Python 2.x 

a={'1':"first", '2':"second" , '3':"third" }
print(a.iteritems())

# <dictionary-itemiterator object at 0x151800fc0cb0>

As seen above, the iteritems() method returns an iterator object. The retrieve the contents of this iterable object, you can iterate through the object elements and with the help of a for loop and print them one by one as shown in the example below:

# Exceuting the code in Python 2.x

a={'1':"first", '2':"second" , '3':"third" }
for i in a.iteritems():
    print i

Output:

('1', 'first')
('3', 'third')
('2', 'second')

As the whole dictionary was not copied, it meant that memory consumption was less in this case. Thus, dict.iteritems() proved to be an enhancement upon the previously used method as it increased the efficiency of the code. So, Python 2 now had two methods dict.items() and dict.iteritems(). However, the problem with the iterator objects was iteration could be performed only once. And if there was a need to perform iteration again, that wasn’t possible. Let’s have a look at the following example to understand this:

# Exceuting the code in Python 2.x
# create a dictionary
a={'1':"first", '2':"second" , '3':"third" }

res=a.iteritems()

print("Iterate for the first time")
#iterate for the first-time
for i in res:
    print i

print("Iterate for the second time")
#iterate for the second time
for j in res:
    print j

print("End of Program")

Output:

Iterate for the first time
('1', 'first')
('3', 'third')
('2', 'second')
Iterate for the second time
End of Program

Discussion: As seen in the above example, once the iterators are used they are exhausted. Hence, when the iteration was performed the second time, nothing was returned because the iterator object was already consumed. Thus, In Python 3, they wanted to further improvise this, so instead of returning an iterator object, the method would return a view object. View object would provide a live view of the current state of the dictionary and can be iterated multiple times.

Thus in Python 3, they removed the Python 2’s dict.items() and then migrated dict.iteritems() method with an improvised functionality and named it as dict.items() 

So, dict.iteritems() in Python 2 is functionally equivalent to dict.items() in Python 3.

Hence, the error ‘dict’ object has no attribute ‘iteritems’ is seen as there is no attribute named iteritems within the dict class in Python 3.

Example:

# Executing the code in Python 3
# create a dictionary
a = {'1': "first", '2': "second", '3': "third"}

# Output the key-value pairs in the dictionary
for i in a.iteritems():
    print(i)

Ouptut:

# Executing the code in Python 3
# create a dictionary
a = {'1': "first", '2': "second", '3': "third"}

# Output the key-value pairs in the dictionary
for i in a.iteritems():
    print(i)

Now that we have understood why the error is seen, let us discuss various ways to fix this error in this article.

Method 1: Use dict.items()

We already know that dict.iteritems() in Python 2 is functionally equivalent to dict.items() in Python 3, hence, use dict.items() instead of dict.iteritems() as shown in the below:

# Executing the code in Python 3#create a dictionary
a = {'1': "first", '2': "second", '3': "third"}
# Output the key-value pairs in the dictionary
for i in a.items():
    print(i)

Output:

('1', 'first')
('2', 'second')
('3', 'third')
  • Note that when we say that dict.itertitems() is equivalent to dict.items(), we say they are the same in terms of functionality. However, in Python 2 dict.iteritems() returns an iterator object and dict.items() in Python 3 returns a view object.
# Exceuting the code in Python 3#create a dictionary
a = {'1':"first", '2':"second" , '3':"third" }
print(type(a.items()))
# <class 'dict_items'>

For some reason, if you want an iterator object instead, convert the view object to an iterator object as shown below:

iter(dict.items())
print(iter(a.items()))

# <dict_itemiterator object at 0x000001AE90E4B9F0>

So, when we execute the below code, we can see that the dict_items class object gets converted to an iterator object.

Method 2: Use Python 2to3 Tool

If you do not want to make any changes manually to your script and run the script without seeing any error, you can use the in-built 2to3 tool that will automatically change the imports in the Python File.

In order to use 2to3 tools, open your terminal and install the tool with the below command-

pip3 install 2to3

Once you have successfully installed the tool, open your terminal and enter the below command –

Syntax :

2to3 -w <path_to_Python2File>

Example: 

Let us say, we have a file named dict_object_test.py with the following contents:

#create a dictionary
a={'1':"first", '2':"second" , '3':"third" }

#Output the key-value pairs in the dictionary
for i in a.items():
  print(i)

If we want to convert this file to Python 3, open the terminal window and execute the below command :

2to3 -w “C:\Users\admin\Desktop\Finxter\dict_object_test.py”

You will see that the tool would convert the file to a Python 3 file as shown below:

(venv) C:\Users\admin\Desktop\Finxter>2to3 -w "C:\Users\admin\Desktop\Finxter\dict_object_test.py"
RefactoringTool: Skipping optional fixer: buffer
RefactoringTool: Skipping optional fixer: idioms
RefactoringTool: Skipping optional fixer: set_literal
RefactoringTool: Skipping optional fixer: ws_comma
RefactoringTool: Refactored C:\Users\admin\Desktop\Finxter\dict_object_test.py
--- C:\Users\admin\Desktop\Finxter\dict_object_test.py  (original)
+++ C:\Users\admin\Desktop\Finxter\dict_object_test.py  (refactored)
@@ -1,4 +1,4 @@
a={'1':"first", '2':"second" , '3':"third" }

-for i in a.iteritems():
+for i in a.items():
    print(i)
RefactoringTool: Files that were modified:
RefactoringTool: C:\Users\admin\Desktop\Finxter\dict_object_test.py

Note that the changes will be made to the file and a backup of the file will be maintained in the same file location.

Method 3: Use Third-Party Modules 

There are some third-party modules that can be imported and used in the Python program. These modules help to come up with a code that is compatible with both Python versions 2 and 3. 

⦿The six library module

The six library module helps to come up with a code that is compatible with Python versions 2.5+ and 3+. It has a method named iteritems() that can be used.

To use the iteritems method from the six module, you have to first install the six module. To do so, open your terminal and enter the below command

pip install six

To use the module, import the six module in your program as shown below

import six

Syntax :

six.iteritems(dict)

Here, dict is the dictionary you want to use.

Example: Let us use the same example with the six.iteritems() method. 

import six

# create a dictionary
a = {'1':"first", '2':"second" , '3':"third" }

# Output the key-value pairs in the dictionary
for i in six.iteritems(a):
  print(i)

Output:

('1', 'first')
('2', 'second')
('3', 'third')

As seen in the above example, there is no error.

⦿The future.utils Library Module

The future module is another third-party library module that can be used to write a code that is compatible with Python versions, 2.6+ and 3.3+. The future module has a submodule named utils that contains the iteritems() method.

To use the future module, we have to first install it. To do so, open your terminal window and type the below command :

pip install future

To use the module, import the future module in your program as shown below

import future.utils as fu

Syntax :

fu.iteritems(dict)

Here, dict is the dictionary you want to use.

Example: 

Let us use the same example with the fu.iteritems() method. 

import future.utils as fu

# create a dictionary
a = {'1': "first", '2': "second", '3': "third"}

# Output the key-value pairs in the dictionary
for i in fu.iteritems(a):
    print(i)

# ('1', 'first')('2', 'second')('3', 'third')

As seen in the above example, no error is thrown.

Conclusion

In this tutorial, we have discussed different ways to fix the error ‘dict’ object has no attribute ‘iteritems’. We hope that this was helpful and you can now avoid getting the error in your code.  Please stay tuned and subscribe for more such tips and tricks.

Happy Pythoning!

Post Credits: Anusha Pai and Shubham Sayon