12

I have a little problem with my networkx code. I am trying to find all the neighbors from a node in a graph, but....

neighbor = Graph.neighbors(element)
print(neighbor)

outputs:

<dict_keyiterator object at 0x00764BA0>

Instead of all the neighbors I am supposed to get... A friend of mine, who is using an older version of networkx does not get this error, his code is exactly the same and works perfectly.

Can anyone help me? Downgrading my networkx is not an option.

Edit:

This is my complete code

Graph = nx.read_graphml('macbethcorrected.graphml')    
actors = nx.nodes(Graph)

for actor in actors:
    degree = Graph.degree(actor)
    neighbor = Graph.neighbors(actor)
    print("{}, {}, {}".format(actor, neighbor, degree))

This is the graph I am using: http://politicalmashup.nl/new/uploads/2013/09/macbethcorrected.graphml

Community
  • 1
  • 1
Joep Groentesoep
  • 165
  • 2
  • 10

3 Answers3

15

From networkx 2.0 onwards, Graph.neighbors(element) returns an iterator rather than a list.

To get the list, simply apply list

list(Graph.neighbors(element))

or use list comprehension:

neighbors = [n for n in Graph.neighbors(element)]

The first method (first mentioned by Joel) is the recommended method, as it's faster.

Reference: https://networkx.github.io/documentation/stable/reference/classes/generated/networkx.Graph.neighbors.html

Fabian Ying
  • 1,216
  • 1
  • 10
  • 15
1

As others have noted, in networkx 2.0 neighbors returns an iterator rather than a list. Networkx has provided a guide for migrating code written in 1.x to 2.0. For neighbors, it recommends

list(G.neighbors(n))

(see Fastest way to convert an iterator to a list). The migration guide provides the example:

>>> G = nx.complete_graph(5)
>>> n = 1
>>> G.neighbors(n)
<dictionary-keyiterator object at ...>
>>> list(G.neighbors(n))
[0, 2, 3, 4]
Joel
  • 22,598
  • 6
  • 69
  • 93
0

You can make method for that like,

def neighbors(G, n):
"""Return a list of nodes connected to node n. """
return list(G.neighbors(n))

And call that method as:

print(" neighbours = ", neighbors(graph,'5'))

Where 5 is the node in a graph and

graph = nx.read_edgelist(path, data = (('weight', float), ))

and path variable contains dataset file path value where data is in more numbers of nodes and edges.

AMI CHARADAVA
  • 303
  • 3
  • 9