August C.
August C.

Reputation: 1

Sorting Edges in a Data Structures Graph

I have a graph with edges that are interconnected. How I would go about sorting the edges of the nodes in the graph from low to high by weight number?

edges = {
    ("a", "b"): 1,
    ("a", "c"): 7,
    ("a", "d"): 3,
    ("b", "c"): 2,
    ("f", "b"): 6,
    ("c", "d"): 1,
    ("c", "e"): 8,
    ("d", "e"): 4,
    ("e", "f"): 1,
    ("f", "g"): 3,
}

Where a-g are nodes and the number is the weight of the edge. Written in python.

Upvotes: 0

Views: 125

Answers (1)

mypetlion
mypetlion

Reputation: 2524

You can extract the dict keys into a list, and then sort the list.

edges = {('a', 'b'): 1, ('a', 'c'): 7, ('a', 'd'): 3, ('b', 'c'): 2, ('f', 'b'): 6, ('c', 'd'): 1, ('c', 'e'): 8, ('d', 'e'): 4, ('e', 'f'): 1, ('f', 'g'): 3}
edgeList = sorted(edges.keys(), key = edges.get)

edges.keys() is a dict method that will get you a dict_keys object. Basically a wrapper object around a list of the keys used in your dict. The second parameter to the sorted function is the criteria that will be used to sort the iterable provided in the first parameter of sorted.

Upvotes: 1

Related Questions