Reputation: 4214
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:
Upvotes: 1
Views: 1084
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