Python:遍历字典会给我一个;int object not iterable“;
以下是我的功能:Python:遍历字典会给我一个;int object not iterable“;,python,dictionary,loops,Python,Dictionary,Loops,以下是我的功能: 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 "co
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
回溯(最近一次呼叫最后一次):
文件“compareScans.py”,第81行,在
printSubnetCountList(subnetCountOld)
printSubnetCountList中第70行的文件“compareScans.py”
对于countList中的k,v:
TypeError:“int”对象不可编辑
有什么想法吗?试试这个
for k in countList:
v = countList[k]
还是这个
for k, v in countList.items():
请读这个:你不能像这样重复口述。见示例:
def printSubnetCountList(countList):
print type(countList)
for k in countList:
if countList[k]:
print "Subnet %d: %d" % k, countList[k]
k,v的
语法是元组解包表示法的一种简短形式,可以写成(k,v)的
。这意味着迭代集合的每个元素都应该是由两个元素组成的序列。但字典上的迭代只产生键,而不产生值
解决方案是使用<代码> DIT.ITMs[(或)代码>或<代码> Dist.ItItItMeSe()/Case>(懒惰变体),它返回关键值元组序列。
<代码>迭代器()/代码>在Python 2中工作,而不是在Python 3中,其等价的是“代码>项目())/>代码>您可能想考虑将类型提示添加到代码中以获得更好的可读性()。