I want to get the edge between two nodes in a networkx graph. More specifically, I want to get some data associated with this edge. I know a priori that these two nodes are linked. Is there a function to do this?
An edge is incident on the two nodes it connects. Any two nodes connected by an edge or any two edges connected by a node are said to be adjacent.
Approach: Either Breadth First Search (BFS) or Depth First Search (DFS) can be used to find path between two vertices. Take the first vertex as a source in BFS (or DFS), follow the standard BFS (or DFS). If the second vertex is found in our traversal, then return true else return false.
One simple option is to do a depth-first search starting at one of the nodes until you reach the other node. You can then look at the path that was taken from the first node to the second, which must be the unique path between those nodes, and then count how many edges are in that path.
The edge data are stored in a dictionary. To access that dictionary, use get_edge_data()
.
import networkx as nx
G=nx.Graph()
G.add_edge(1,2, weight=5)
G.get_edge_data(1,2)
> {'weight': 5}
If you want to iterate through all the edges you can use G.edges(data=True)
H = nx.Graph()
H.add_edge(2, 3, color = 'red')
H.add_edge(1, 2, weight = 4)
for u,v,data in H.edges(data=True):
print(u, v, data)
> 1 2 {'weight': 4}
> 2 3 {'color': 'red'}
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