2011-04-21 127 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()(懒惰变体),它返回键值元组的序列。