how to add parametr to existing edges of a networkx graph in python

To add parameter to existing edges in a Networkx graph, you can use the set_edge_attributes() function. This function sets one or more parameters of the edge.

Here's an example:

main.py
import networkx as nx

# create a graph
G = nx.Graph()

# add edges
G.add_edge('A', 'B')
G.add_edge('B', 'C')

# create a dictionary of parameters to add to the edges
params = {('A', 'B'): {'weight': 3}, ('B', 'C'): {'weight': 5}}

# set the edge parameters
nx.set_edge_attributes(G, params)

# print the edges and their parameters
print(G.edges.data())
354 chars
18 lines

Output:

main.py
[('A', 'B', {'weight': 3}), ('B', 'C', {'weight': 5})]
55 chars
2 lines

In the params dictionary, the keys are tuples representing edges and the values are dictionaries of parameters to set for the edges. The set_edge_attributes() function takes two arguments: the graph and the dictionary of parameters.

This will set the weight parameter to 3 for the edge ('A', 'B') and 5 for the edge ('B', 'C').

Note that you can also use the add_edge() function to add new edges with parameters directly.

related categories

gistlibby LogSnag