Python:遍历字典时出现“int object not iterable”错误。

40

这是我的函数:

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

有什么想法吗?


你可能想要考虑在你的代码中添加类型提示,以提高可读性(https://www.python.org/dev/peps/pep-0484/)。 - Thomas Fritz
3个回答

54

20
for k, v语法是元组解包符号的简化形式,也可以写作for (k,v)。这意味着迭代集合的每个元素都应该是一个包含两个元素的序列。但是,对字典进行迭代时只会返回键而不是值。

解决方案是使用dict.items()dict.iteritems()(懒惰变量),它们返回键-值元组的序列。


iteritems()Python2中可用,但在Python3中不再支持,其等效方法为items()相关问题请参考Stack Overflow - datapug

2
您不能像这样迭代字典。请参见以下示例:
def printSubnetCountList(countList):
    print type(countList)
    for k in countList:
        if countList[k]:
            print "Subnet %d: %d" % k, countList[k]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接