2015-05-23 35 views
163

我試圖使用NetworkX讀取Shapefile並使用函數write_shp()來生成將包含節點和邊(以下這個例子 - https://networkx.github.io/documentation/latest/reference/readwrite.nx_shp.html),但是當我嘗試運行它給了我下面的錯誤代碼:錯誤「'字典'對象沒有屬性'iteritems'」當試圖使用NetworkX的write_shp()

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' 

我使用Python 3.4和安裝NetworkX通過PIP安裝。

在這個錯誤之前,它已經給了我另一個說「xrange不存在」或類似的東西,所以我查了一下,然後在nx_shp.py文件中將'xrange'改爲'range'似乎解決了它。

從我讀過的內容可能與Python版本(Python2 vs Python3)有關。

+60

Python 3重命名爲'dict.iteritems - > dict.items'。 – Blender

+1

哦哇我現在感覺很傻,謝謝你的回答 – friveraa

+4

@Blender:不,它沒有將'iteritems'重命名爲'items'。前者給你一個迭代器(而3.x沒有這種方法);後者給你一個視圖(它被視爲「視圖」)。 – abarnert

回答

369

正如你在python3,使用dict.items()代替dict.iteritems()

iteritems()在python3被刪除,所以你不能用這種方法了。

看看Python的維基(Link

內置變化一部分,它指出,

Removed dict.iteritems(), dict.iterkeys(), and dict.itervalues().

Instead: use dict.items(), dict.keys(), and dict.values() respectively.

+4

將其更改爲dict.items()並按預期工作,謝謝! – friveraa

+1

'dict.items()'也可以在python 2.7 – industryworker3595112

+0

中使用[PEP 469](http://legacy.python.org/dev/peps/pep-0469/)對此進行了進一步的討論。推薦的方法似乎是使用'future.utils'或'six'模塊的'iteritems'功能。 – Mack

3

我有(使用3.5)有類似的問題,失去了1 /每天2次,但這裏有一些有用的東西 - 我退休了,只是學習Python,所以我可以幫助我的孫子(12)。

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 
7

Python2,我們在字典.items().iteritems()dict.items()返回字典中的元組列表[(k1,v1),(k2,v2),...]。它複製了字典中的所有元組並創建了新列表。如果字典非常大,則會有很大的內存影響。

因此,他們在更高版本的Python2中創建了dict.iteritems()。這個返回的迭代器對象。整個字典沒有被複制,所以內存消耗較少。教導使用Python2的人員使用dict.iteritems()而不是.items()來提高效率,如以下代碼所解釋的。

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 

輸出:

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

Python3,他們想使之更有效率,所以移動dictionary.iteritems()dict.items(),並刪除.iterates(),因爲它不再需要。

您在Python3中使用了dict.iterates(),因此它失敗了。嘗試使用dict.items()其功能與Python2dict.iteritems()具有相同的功能。這是一個微小的遷移問題,從Python2Python3

3

在Python2,dictionary.iteritems()的效率比dictionary.items()所以在Python3,的dictionary.iteritems()功能已遷移到dictionary.items()iteritems()被去除。所以你得到這個錯誤。

在Python3中使用dict.items(),它與Python2的dict.iteritems()相同。

相關問題