how to add graph weights in python

In Python, you can represent a graph using a dictionary or an adjacency list. To add weights to the edges of the graph, you just need to modify the values of the dictionary to include a tuple for each edge, where the first element of the tuple is the weight of the edge.

Here is an example code snippet:

main.py
# create the graph
graph = {
    'A': {'B': 2, 'C': 1},
    'B': {'D': 3},
    'C': {'D': 2},
    'D': {}
}

# iterate through the graph and print the weights
for node in graph:
    for neighbor in graph[node]:
        print(f'Weight from {node} to {neighbor}: {graph[node][neighbor]}')
287 chars
13 lines

In the above code block, each node in the graph is represented by a key in the Python dictionary. The value of each key is another dictionary where the keys represent the neighbors of that node and the values are the weights of the edges between the nodes.

To print the weights of all edges, we simply iterate through all the nodes and their neighbors and print the weight of the edge by accessing the value of the dictionary using the node and neighbor keys.

related categories

gistlibby LogSnag