40

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?

Dan
  • 451
  • 2
  • 5
  • 4
  • You may want to consider adding type hints to your code for better readability (https://www.python.org/dev/peps/pep-0484/) – Thomas Fritz Feb 28 '21 at 18:16

3 Answers3

53

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

wjandrea
  • 28,235
  • 9
  • 60
  • 81
S.Lott
  • 384,516
  • 81
  • 508
  • 779
20

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.

Adam Byrtek
  • 12,011
  • 2
  • 32
  • 32
  • `iteritems()` works in **Python2**, but not in **Python3** where its equivalent is `items()` [SO related question](https://stackoverflow.com/questions/30418481/error-dict-object-has-no-attribute-iteritems/30418498) – datapug Feb 03 '19 at 11:30
2

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]
sinan
  • 6,809
  • 6
  • 38
  • 67