Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Networkx neighbor set not printing

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

like image 885
Joep Groentesoep Avatar asked Nov 07 '17 15:11

Joep Groentesoep


People also ask

Can NetworkX handle large graphs?

For NetworkX, a graph with more than 100K nodes may be too large. I'll demonstrate that it can handle a network with 187K nodes in this post, but the centrality calculations were prolonged. Luckily, there are some other packages available to help us with even larger graphs.

What is Nbunch in NetworkX?

nbunch. An nbunch is a single node, container of nodes or None (representing all nodes). It can be a list, set, graph, etc.. To filter an nbunch so that only nodes actually in G appear, use G.

How do I display a graph in NetworkX?

Draw the graph G using Matplotlib. Draw the nodes of the graph G. Draw the edges of the graph G. Draw node labels on the graph G.

How do I find nodes of neighbors in Python?

Use the len() and list() functions together with the . neighbors() method to calculate the total number of neighbors that node n in graph G has. If the number of neighbors of node n is equal to m , add n to the set nodes using the . add() method.


1 Answers

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

like image 197
Fabian Ying Avatar answered Nov 08 '22 03:11

Fabian Ying