Search code examples
pythonpython-3.xnetworkx

How to get length of a dictionary iterator?


I am trying to check how many neighbours are there in the graph in the networkx object.

neighbours = nxobject.neighbors('Something')
print(len(neighbours))

Error:

TypeError: object of type 'dict_keyiterator' has no len()

It works with print(len(list(neighbours))) but a new problem arises:

print(len(list(neighbours))) 
for child in neighbours: 
  #Do some work 
    return Done_work 
return None 

Now, I'm getting this error:

TypeError: 'NoneType' object is not subscriptable 

Solution

  • An iterator can be used only once. Convert it to a list, then measure the length of the list and/or use that list for further processing:

    neighbours = list(nxobject.neighbors('Something'))
    print(len(neighbours))