vkaul11
vkaul11

Reputation: 4214

Sorting dictionary-represented graph edges by value/weight

I had the following given representation of Graph Edges in python where the vertices are the keys and the edge weights are the values.

Edges = {(1,2):8.3 , (2,3): 4, (3,1):6}

I need to sort the Edges by weight for one application (Kruskal's algorithm). So given that dictionary is unsorted, I want to convert the Dictionary to a List of Tuples as below.

  Edges_List = [(1,2,8.3), (2,3,4), (3,1,6)] 

These can be sorted by third element of tuple as key. I used this

 Edges_list = [(k,v) for k,v in Edges.items()] 

but I get a nested tuple using this.

 Edges_List = [((1,2),8.3), ((2,3),4), ((3,1),6)]

I have two questions:

  1. How can I create a tuple of three instead of a nested tuple that I get above?
  2. Is there any other approach so that I can sort the Edges dictionary by weight which is a dictionary value apart from converting it into a list of tuples?

Upvotes: 1

Views: 1084

Answers (1)

ersran9
ersran9

Reputation: 978

Use tuple unpacking as follows

>>> import operator
>>> Edges = {(1,2):8.3 , (2,3): 4, (3,1):6}
>>> Edges_list = [(k1,k2,v) for (k1,k2),v in Edges.items() ]
>>> Edges_list
[(1, 2, 8.3), (3, 1, 6), (2, 3, 4)]
>>> Edges_list.sort(key=operator.itemgetter(2))
>>> Edges_list
[(2, 3, 4), (3, 1, 6), (1, 2, 8.3)]

If you want the sorted elements in a loop with your dictionary itself, you could use this

>>> for k,v in sorted(Edges, key=Edges.get):
...     # do stuff with edges

Notice that k and v are your co-ordinates in this case.

Upvotes: 0

Related Questions