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.
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
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With