2011-04-21 174 views
29

這裏是我的功能:的Python:迭代通過一本字典給我「int對象不是可迭代」

def printSubnetCountList(countList): 
    print type(countList) 
    for k, v in countList: 
     if value: 
      print "Subnet %d: %d" % key, value 

下面是當函數調用傳遞給它的字典中的輸出:

<type 'dict'> 
Traceback (most recent call last): 
    File "compareScans.py", line 81, in <module> 
    printSubnetCountList(subnetCountOld) 
    File "compareScans.py", line 70, in printSubnetCountList 
    for k, v in countList: 
TypeError: 'int' object is not iterable 

有任何想法嗎?

回答

0

不能重複這樣的字典。見例如:

def printSubnetCountList(countList): 
    print type(countList) 
    for k in countList: 
     if countList[k]: 
      print "Subnet %d: %d" % k, countList[k] 
12

for k, v語法是元組拆包符號的短形式,並且可以寫成for (k, v)。這意味着迭代集合的每個元素都應該是由兩個元素組成的序列。但是對詞典的迭代只會產生密鑰,而不是數值。

解決方案是使用dict.items()dict.iteritems()(懶惰變體),它返回鍵值元組的序列。