Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a networkx graph object Python

I want to sort a graph object that I have read through networkx library in Python, in the increasing order of edgeweight. It seems that the sort command of python won't apply to graph objects. I am sure there is a easy way to sort this object, but I am not sure how. Any help will be appreciated.

For example, my first three edges are

1 3 5250
1 4 74
1 5 3659

After sorting I would hope that their order is changed to

1 4 74
1 5 3659
1 3 5250

Here is my code so far

import networkx as nx
g=nx.read_weighted_edgelist(fname,nodetype=int)

I am trying to sort the object g.

like image 382
hardikudeshi Avatar asked Dec 23 '12 14:12

hardikudeshi


1 Answers

import networkx as nx
edgelist = [
    (1, 3, {'weight':5250}),
    (1, 4, {'weight': 74}),
    (1, 5, {'weight': 3659})]

G = nx.Graph(edgelist)
for a, b, data in sorted(G.edges(data=True), key=lambda x: x[2]['weight']):
    print('{a} {b} {w}'.format(a=a, b=b, w=data['weight']))

yields

1 4 74
1 5 3659
1 3 5250
like image 50
unutbu Avatar answered Sep 20 '22 18:09

unutbu