get weights of each edge in graph networkx in python

You can get the weight of each edge in a networkx graph in python as follows:

main.py
import networkx as nx

# create a graph
G = nx.Graph()

# add edges with weights
G.add_edge('A', 'B', weight=3)
G.add_edge('B', 'C', weight=4)
G.add_edge('A', 'C', weight=2)

# get the weight of each edge
weights = nx.get_edge_attributes(G, 'weight')

# print the weights
print(weights)
287 chars
16 lines

Output:

main.py
{('A', 'B'): 3, ('A', 'C'): 2, ('B', 'C'): 4}
46 chars
2 lines

Explanation:

  • First, we import the networkx library.
  • Then, we create an empty graph G.
  • We add edges ('A', 'B'), ('B', 'C'), and ('A', 'C') with weights 3, 4, and 2, respectively.
  • We use the get_edge_attributes() function to get the weight of each edge. This function returns a dictionary with edge tuples as keys and their corresponding weight as values.
  • Finally, we print the weights.

related categories

gistlibby LogSnag