Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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


Solution 2:

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.


Solution 3:

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]

Post a Comment for "Python: Iterating Through A Dictionary Gives Me "int Object Not Iterable""