Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>     printSubnetCountList(subnetCountOld)   File "compareScans.py", line 70, in printSubnetCountList     for k, v in countList: TypeError: 'int' object is not iterable 

Any ideas?

like image 204
Dan Avatar asked Apr 21 '11 22:04

Dan


People also ask

How do I fix int object is not iterable in Python?

How to Fix Int Object is Not Iterable. One way to fix it is to pass the variable into the range() function. In Python, the range function checks the variable passed into it and returns a series of numbers starting from 0 and stopping right before the specified number.

Is dictionary an iterable object in Python?

Dictionaries are themselves not an iterator (which can only be iterated over once). You usually make them an iterable, an object for which you can produce multiple iterators instead.

How do you make a dictionary iterable in Python?

To iterate through a dictionary in Python, there are four main approaches you can use: create a for loop, use items() to iterate through a dictionary's key-value pairs, use keys() to iterate through a dictionary's keys, or use values() to iterate through a dictionary's values.


1 Answers

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

like image 174
S.Lott Avatar answered Sep 24 '22 13:09

S.Lott