[python] Error: " 'dict' object has no attribute 'iteritems' "

I'm trying to use NetworkX to read a Shapefile and use the function write_shp() to generate the Shapefiles that will contain the nodes and edges, but when I try to run the code it gives me the following error:

Traceback (most recent call last):   File
"C:/Users/Felipe/PycharmProjects/untitled/asdf.py", line 4, in
<module>
    nx.write_shp(redVial, "shapefiles")   File "C:\Python34\lib\site-packages\networkx\readwrite\nx_shp.py", line
192, in write_shp
    for key, data in e[2].iteritems(): AttributeError: 'dict' object has no attribute 'iteritems'

I'm using Python 3.4 and installed NetworkX via pip install.

Before this error it had already given me another one that said "xrange does not exist" or something like that, so I looked it up and just changed xrange to range in the nx_shp.py file, which seemed to solve it.

From what I've read it could be related to the Python version (Python2 vs Python3).

This question is related to python python-3.x dictionary

The answer is


In Python2, dictionary.iteritems() is more efficient than dictionary.items() so in Python3, the functionality of dictionary.iteritems() has been migrated to dictionary.items() and iteritems() is removed. So you are getting this error.

Use dict.items() in Python3 which is same as dict.iteritems() of Python2.


In Python2, we had .items() and .iteritems() in dictionaries. dict.items() returned list of tuples in dictionary [(k1,v1),(k2,v2),...]. It copied all tuples in dictionary and created new list. If dictionary is very big, there is very big memory impact.

So they created dict.iteritems() in later versions of Python2. This returned iterator object. Whole dictionary was not copied so there is lesser memory consumption. People using Python2 are taught to use dict.iteritems() instead of .items() for efficiency as explained in following code.

import timeit

d = {i:i*2 for i in xrange(10000000)}  
start = timeit.default_timer()
for key,value in d.items():
    tmp = key + value #do something like print
t1 = timeit.default_timer() - start

start = timeit.default_timer()
for key,value in d.iteritems():
    tmp = key + value
t2 = timeit.default_timer() - start

Output:

Time with d.items(): 9.04773592949
Time with d.iteritems(): 2.17707300186

In Python3, they wanted to make it more efficient, so moved dictionary.iteritems() to dict.items(), and removed .iteritems() as it was no longer needed.

You have used dict.iteritems() in Python3 so it has failed. Try using dict.items() which has the same functionality as dict.iteritems() of Python2. This is a tiny bit migration issue from Python2 to Python3.


As answered by RafaelC, Python 3 renamed dict.iteritems -> dict.items. Try a different package version. This will list available packages:

python -m pip install yourOwnPackageHere==

Then rerun with the version you will try after == to install/switch version


I had a similar problem (using 3.5) and lost 1/2 a day to it but here is a something that works - I am retired and just learning Python so I can help my grandson (12) with it.

mydict2={'Atlanta':78,'Macon':85,'Savannah':72}
maxval=(max(mydict2.values()))
print(maxval)
mykey=[key for key,value in mydict2.items()if value==maxval][0]
print(mykey)
YEILDS; 
85
Macon

The purpose of .iteritems() was to use less memory space by yielding one result at a time while looping. I am not sure why Python 3 version does not support iteritems()though it's been proved to be efficient than .items()

If you want to include a code that supports both the PY version 2 and 3,

try:
    iteritems
except NameError:
    iteritems = items

This can help if you deploy your project in some other system and you aren't sure about the PY version.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to python-3.x

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation Replace specific text with a redacted version using Python Upgrade to python 3.8 using conda "Permission Denied" trying to run Python on Windows 10 Python: 'ModuleNotFoundError' when trying to import module from imported package What is the meaning of "Failed building wheel for X" in pip install? How to downgrade python from 3.7 to 3.6 I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? Iterating over arrays in Python 3 How to upgrade Python version to 3.7?

Examples related to dictionary

JS map return object python JSON object must be str, bytes or bytearray, not 'dict Python update a key in dict if it doesn't exist How to update the value of a key in a dictionary in Python? How to map an array of objects in React C# Dictionary get item by index Are dictionaries ordered in Python 3.6+? Split / Explode a column of dictionaries into separate columns with pandas Writing a dictionary to a text file? enumerate() for dictionary in python