Python:通过字典迭代给我"int object not iterable"

Dan*_*Dan 34 python dictionary loops

这是我的功能:

def printSubnetCountList(countList):
    print type(countList)
    for k, v in countList:
        if value:
            print "Subnet %d: %d" % key, value
Run Code Online (Sandbox Code Playgroud)

这是通过传递给它的字典调用函数时的输出:

<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
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

S.L*_*ott 50

试试这个

for k in countList:
    v= countList[k]
Run Code Online (Sandbox Code Playgroud)

或这个

for k, v in countList.items():
Run Code Online (Sandbox Code Playgroud)

请阅读此内容:http://docs.python.org/library/stdtypes.html#mapping-types-dict


Ada*_*tek 17

for k, v语法是元组拆包符号的短形式,并且可以写成for (k, v).这意味着迭代集合的每个元素都应该是一个由两个元素组成的序列.但是对字典的迭代只产生键,而不是值.

解决方案是使用dict.items()或者dict.iteritems()(懒惰变体),它返回键值元组的序列.