add edges with weights to newtorkx digraph in python

To add edges with weights to a newtorkx digraph, you can use the add_weighted_edges_from() method. Here's an example code snippet:

main.py
import networkx as nx

G = nx.DiGraph()

# add edges with weights
G.add_weighted_edges_from([(0, 1, 0.5), (1, 2, 0.75), (2, 3, 1.2)])

# print graph
print(G.edges(data=True))
175 chars
10 lines

In the above code, we first create a new directed graph G. We then add three edges (0,1), (1,2), (2,3) with weights 0.5, 0.75, and 1.2, respectively, using the add_weighted_edges_from() method. Finally, we print the graph using the edges() method with the data=True argument to display the weights of the edges.

Output:

main.py
[(0, 1, {'weight': 0.5}),
 (1, 2, {'weight': 0.75}),
 (2, 3, {'weight': 1.2})]
79 chars
4 lines

related categories

gistlibby LogSnag