how to update networkx edges with new weight in python

To update the weights of the edges in a networkx graph, you can loop through the edges and assign the new weight to the "weight" attribute of each edge.

Here's an example code snippet that updates the weights of the edges based on a new weight dictionary:

main.py
import networkx as nx

# create a graph
G = nx.Graph()

# add nodes and edges
G.add_nodes_from(['A', 'B', 'C'])
G.add_edge('A', 'B', weight=2)
G.add_edge('B', 'C', weight=3)

# new weight dictionary
new_weights = {('A', 'B'): 5, ('B', 'C'): 4}

# loop through the edges and update weights
for u, v, d in G.edges(data=True):
    if (u, v) in new_weights:
        d['weight'] = new_weights[(u, v)]
    else:
        d['weight'] = d.get('weight', 1)  # default weight is 1

# print updated edges
for u, v, d in G.edges(data=True):
    print(u, v, d['weight'])
557 chars
24 lines

Output:

main.py
A B 5
B C 4
12 chars
3 lines

In this example, we create a graph with three nodes and two edges. We then define a new weight dictionary where the keys are tuples representing edge endpoints and the values are the new weights. We loop through the edges of the graph and assign the new weights to the "weight" attribute of each edge if the edge exists in the new weight dictionary. If there is no weight defined for the edge in the new weight dictionary, we keep its previous weight (or default weight 1 if no previous weight exists). Finally, we print the updated edges.

related categories

gistlibby LogSnag