的Python:迭代通过一本字典给我“int对象不是可迭代”
问题描述:
这里是我的功能:的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
有任何想法吗?
答
试试这个
for k in countList:
v= countList[k]
或者这
for k, v in countList.items():
阅读,请:http://docs.python.org/library/stdtypes.html#mapping-types-dict
答
不能重复这样的字典。见例如:
def printSubnetCountList(countList):
print type(countList)
for k in countList:
if countList[k]:
print "Subnet %d: %d" % k, countList[k]
答
的for k, v
语法是元组拆包符号的短形式,并且可以写成for (k, v)
。这意味着迭代集合的每个元素都应该是由两个元素组成的序列。但是对词典的迭代只会产生密钥,而不是数值。
解决方案是使用dict.items()
或dict.iteritems()
(懒惰变体),它返回键值元组的序列。
这么简单,但工作。谢谢! – Dan 2011-04-21 23:04:43