Sarath
Sarath

Reputation: 313

How can I get the weight of an undirected edge in networkx?

import networkx as nx 

G=nx.Graph()

connections = [(0, 1, 4), (0, 7, 8), (1, 7, 11),(1, 2, 8), (2, 8, 2), (7, 8, 7), 
               (7, 6, 1), (8, 6, 6), (2, 5, 4), (6, 5, 2), (2, 3, 7), (3, 5, 14),
               (3, 4, 9), (5, 4, 10), ]

G.add_weighted_edges_from(connections)

In this code, how can I get the weight between two nodes? (i.e) 5 and 4 ?

Upvotes: 2

Views: 1760

Answers (1)

Joel
Joel

Reputation: 23907

For one edge:

G.edges[5,4]['weight']
> 4

For all edges of one node:

G.edges(5, data=True)
> EdgeDataView([(5, 2, {'weight': 4}), (5, 6, {'weight': 2}), (5, 3, {'weight': 14}), (5, 4, {'weight': 10})])

For all edges:

for u, v, w in G.edges(data=True):
    print(u, v, w['weight'])

> 0 1 4
> 0 7 8
> 1 7 11
> 1 2 8
> 7 8 7
> 7 6 1
> 2 8 2
> 2 5 4
> 2 3 7
> 8 6 6
> 6 5 2
> 5 3 14
> 5 4 10
> 3 4 9

Upvotes: 3

Related Questions