开发者

Python: Iterating through a dictionary gives me "int object not iterable"

Here's my function:

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

Here's the output when the function is called with the dictionary passed to it:

<type 'dict'>
Traceback (most recent call last):
  File "compareScans.py", line 81, in <module>
    pri开发者_Go百科ntSubnetCountList(subnetCountOld)
  File "compareScans.py", line 70, in printSubnetCountList
    for k, v in countList:
TypeError: 'int' object is not iterable

Any ideas?


Try this

for k in countList:
    v = countList[k]

Or this

for k, v in countList.items():

Read this, please: Mapping Types — dict — Python documentation


The for k, v syntax is a short form of the tuple unpacking notation, and could be written as for (k, v). This means that every element of the iterated collection is expected to be a sequence consisting of exactly two elements. But iteration on dictionaries yields only keys, not values.

The solution is it use either dict.items() or dict.iteritems() (lazy variant), which return sequence of key-value tuples.


You can't iterate a dict like this. See example:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜