add edge weights to existing nodes in graph networkx in python

You can add edge weights in networkx by setting the "weight" parameter in the add_edge function.

Here's an example:

main.py
import networkx as nx

G = nx.Graph()
G.add_node(1)
G.add_node(2)
G.add_edge(1, 2, weight=3)
print(G.edges(data=True)) # output: [(1, 2, {'weight': 3})]
153 chars
8 lines

In the above code snippet, we first create an empty Graph G. Then, we add two nodes 1, 2 using the add_node function. Finally, we add an edge between 1 and 2 with a weight of 3 using the add_edge function.

To view the weight of edges in the graph, we can pass the data=True parameter to the edges function. This will return a list of edges along with their respective weights.

I hope this helps!

related categories

gistlibby LogSnag