Python throws error, ‘dict’ object has no attribute ‘iteritems’, because iteritems() function is removed from Python 3. Similarly, functions like iterkeys() and itervalues() are also removed.

According to Python3.0 Built-in changes documentation

Remove dict.iteritems(), dict.iterkeys(), and dict.itervalues(). Instead: use dict.items(), dict.keys(), and dict.values() respectively.

So, instead of .iteritems() you can use .items().

You encounter this error when you are migrating from Python 2 to Python 3. There are many other changes which you can see in the documentation link, I shared above.

Why Python 3 removed iteritems()?

According to PythonSpeed documentation, iterator forms are preferred as they are optimized. So, .iteritems() is preferred over .items(). In Python 2, we had both items() as well as iteritems(). The difference between the two of them is –

  • items() copies the whole dictionary and returns it. If the size of dictionary is large, it will consume a lot of memory, which is bad for performance.
  • iteritems() acts as a pointer and do not make a copy of dictionary. So, its good to use.

In Python 3, the team decided to optimize items() function and drop iteritems() completely. That’s why we get the error ‘dict’ has no attribute like iteritems or iterkeys or itervalues.

Code Example

SuperHeroDict = {
    "Steve": "Captain America",
    "Tony" : "Ironman",
    "Bruce": "Hulk",
    "Clint": "Hawkeye",
    "Scott": "Ant Man",
    "Sam"  : "Falcon",
    "Wanda": "Scarlet Witch",

for key,value in SuperHeroDict.iteritems():
    print(key + " is " + value)

# will work fine in python 2
# Python 3: Error: 'dict' object has no attribute 'iteritems'

    Tweet this to help others


About the Author


I am Akash Mittal, an overall computer scientist. If you want to guest post, need help in your projects, want to advertise, Feel free to contact me at [email protected]

View All Articles