Lalit
Lalit

Reputation: 21

Sort weighted undirected graph in python

I need to sort below graph based on the weights.

    graph_G = {'A': [('B', 7), ('E', 2)],
       'B': [('C', 6)],
       'C': [('A', 5), ('D', 3)],
       'D': [('E', 1)],
       'E': [('A', 7)],
      }

I have tried print("Sort Dict %s" % (sorted(graph_G.items(), key=itemgetter(1))))

This is sorting the dictionary on the first char of the tuple. I would like to sort it on the 2nd part of the tuple (weights).

So I want it sorted like below.

graph_G = {'A': [('E', 2), ('B', 7)],
       'B': [('C', 6)],
       'C': [('D', 3), ('A', 5)],
       'D': [('E', 1)],
       'E': [('A', 7)],
      }

Is there any way to get this done?

Upvotes: 0

Views: 166

Answers (1)

Elena Belkina
Elena Belkina

Reputation: 11

graph_G = {
'A': [('B', 7), ('E', 2)],
'B': [('C', 6)],
'C': [('A', 5), ('D', 3)],
'D': [('E', 1)],
'E': [('A', 7)]
}

sorted_graph_G = {node: sorted(neighbors, key=lambda x: x[1]) for node, neighbors in graph_G.items()}

print("Sorted graph based on weights:")
for node, neighbors in sorted_graph_G.items():
print(f"{node}: {neighbors}")

The output:

Sorted graph based on weights:
A: [('E', 2), ('B', 7)]
B: [('C', 6)]
C: [('D', 3), ('A', 5)]
D: [('E', 1)]
E: [('A', 7)]

Upvotes: 0

Related Questions