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

后端 未结 3 1929
不知归路
不知归路 2020-12-14 14:57

Here\'s my function:

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


        
相关标签:
3条回答
  • 2020-12-14 15:19

    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 讨论(0)
  • 2020-12-14 15: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.

    0 讨论(0)
  • 2020-12-14 15:32

    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

    0 讨论(0)
提交回复
热议问题