get weights of each edge in digraph networkx in python in python

You can use the edges() method to get all edges in the directed graph and then use the get() method on the edge to get the weight of each edge.

Here's an example:

main.py
import networkx as nx

# Create a directed graph
G = nx.DiGraph()

# Add edges with weights
G.add_edge('a', 'b', weight=3)
G.add_edge('b', 'c', weight=4)
G.add_edge('c', 'd', weight=2)

# Get weights of each edge
for u, v, weight in G.edges(data='weight'):
    print(f"Weight of ({u}, {v}) is {weight}")
304 chars
14 lines

This will output:

main.py
Weight of (a, b) is 3
Weight of (b, c) is 4
Weight of (c, d) is 2
66 chars
4 lines

You can modify the print() statement to store the weights in a list or dictionary if needed.

related categories

gistlibby LogSnag