Python: 遍历字典时出现“int对象不可迭代”

40 投票
3 回答
54131 浏览
提问于 2025-04-16 16:12

这是我的函数:

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

有什么想法吗?

3 个回答

2

你不能这样遍历一个字典。看看这个例子:

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

for k, v 这种写法其实是一个简化的方式,用来同时获取两个值,可以理解为 for (k, v)。这意味着你在遍历的集合中的每个元素都应该是一个包含两个元素的序列。不过,当你遍历字典的时候,只能得到键,而不能直接得到值。

解决这个问题的方法是使用 dict.items() 或者 dict.iteritems()(后者是懒惰的版本),这两个方法会返回一个包含键值对的序列。

54

试试这个

for k in countList:
    v = countList[k]

或者这个

for k, v in countList.items():

请阅读这个:映射类型 — dict — Python文档

撰写回答