Sub topic 4
Weighted graphs: edges that carry a value
This chapter assumes you can read Python dictionaries and nested dictionaries, and that you know what vertices, edges, and the undirected and directed cases are. Weights are a separate property from direction. Any graph, directed or undirected, can be weighted.
What a weight is
A weighted graph attaches a number to every edge. The number is called the edge's weight. What it means depends on the problem:
- Cost: the price of a flight between two airports.
- Distance or time: the minutes needed to drive between two towns.
- Capacity: the maximum traffic a network link can carry.
- Strength: how similar two items are, or how likely a transition is.
The graph structure only says whether two vertices are connected. The weight says how much that connection is worth. Questions change as a result. In an unweighted graph you ask for the path with the fewest edges. In a weighted graph you usually ask for the path with the smallest total weight, and the two answers can differ.
Weight and direction combine freely:
| Graph | Edge A to B | Edge B to A |
|---|---|---|
| Undirected, weighted | One edge, one weight | The same edge, the same weight |
| Directed, weighted | Weight 5 | A separate edge, possibly weight 9, or no edge |
In a directed weighted graph the two directions are independent edges. A road with a steep uphill direction might take 20 minutes one way and 8 the other.
Storing weights in an adjacency list
The adjacency list in this tutorial is a dictionary of dictionaries. The outer key is a vertex. The inner dictionary maps each neighbor to the weight of the edge leading there. An unweighted graph is the special case where every weight is 1, which is why add_edge defaults weight to 1.
def add_edge(graph, u, v, weight=1, directed=False):
graph.setdefault(u, {})[v] = weight
graph.setdefault(v, {})
if not directed:
graph[v][u] = weight
weighted = {}
add_edge(weighted, "A", "B", 4)
add_edge(weighted, "A", "C", 1)
add_edge(weighted, "C", "B", 2)
print(weighted)
# {'A': {'B': 4, 'C': 1}, 'B': {'A': 4, 'C': 2}, 'C': {'A': 1, 'B': 2}}
print(weighted["A"]["B"]) # 4Looking up the weight of a known edge is graph[u][v], which takes constant time on average. Iterating over graph[u].items() gives each neighbor together with its weight, which is the loop shape most weighted algorithms use.
The undirected edge appears twice, once under each endpoint, with the same weight. If you update one copy and forget the other, the graph silently becomes inconsistent. Always change weights through a function that handles both directions.
The diagram below shows the graph just built.
Path weight
The weight of a path is the sum of the weights of the edges along it. A path's length in edges and its weight are different quantities.
def path_weight(graph, path):
total = 0
for u, v in zip(path, path[1:]):
if v not in graph[u]:
raise ValueError(f"no edge from {u} to {v}")
total += graph[u][v]
return total
print(path_weight(weighted, ["A", "B"])) # 4
print(path_weight(weighted, ["A", "C", "B"])) # 3The path A, B uses one edge and weighs 4. The path A, C, B uses two edges and weighs 3. Breadth-first search would report the first as shortest because it counts edges. A weighted shortest-path algorithm reports the second. Dijkstra's algorithm, covered later in this tutorial, computes this for every vertex at once.
The function checks v not in graph[u] rather than catching a KeyError, so it can give a readable message. For a directed graph the check also enforces direction, because graph[u] only contains edges leaving u.
Listing each edge once
Many weighted algorithms, such as minimum spanning tree methods, work on a list of edges instead of on neighbors. In an undirected adjacency list every edge appears twice, so a naive loop double counts. This function emits each undirected edge once by keeping only the direction where u <= v.
def edge_list(graph, directed=False):
result = []
for u in graph:
for v, w in graph[u].items():
if directed or u <= v:
result.append((u, v, w))
return result
edges = edge_list(weighted)
print(edges) # [('A', 'B', 4), ('A', 'C', 1), ('B', 'C', 2)]
print(sum(w for _, _, w in edges)) # 7The total weight of the graph is 7. Summing over graph[u].values() for every u would give 14, which is a common mistake. The u <= v trick requires vertex labels that can be ordered. With mixed label types, track a set of already seen frozenset({u, v}) pairs instead.
Edge cases and common errors
Zero is a valid weight
A weight of 0 is legal, for example a free transfer between two stations. Testing for an edge with truthiness breaks on it.
g = {}
add_edge(g, "X", "Y", 0)
print(bool(g["X"].get("Y"))) # False, wrongly suggests there is no edge
print("Y" in g["X"]) # True, the correct testTest for an edge with v in graph[u], never with the weight's truthiness. Likewise, do not use 0 or None as a "no edge" marker in a dictionary representation. The absence of the key is the marker.
Parallel edges are overwritten
A dictionary holds one value per neighbor, so adding a second edge between the same pair replaces the first. This model is called a simple graph. If your data contains several routes between the same two vertices, decide what the duplicates mean. Often you want the cheapest one:
def add_min_edge(graph, u, v, weight, directed=False):
if v in graph.get(u, {}) and graph[u][v] <= weight:
return
add_edge(graph, u, v, weight, directed)
m = {}
add_min_edge(m, "A", "B", 7)
add_min_edge(m, "A", "B", 5)
add_min_edge(m, "A", "B", 9)
print(m["A"]["B"]) # 5If you need to keep all parallel edges, store a list of weights per neighbor, or give each edge an identifier. That is a multigraph, and most algorithms in this tutorial assume you have already reduced it to a simple graph.
Self-loops
An edge from a vertex to itself is stored as graph[u][u] = w. In an undirected graph add_edge writes the same entry twice, which is harmless. With non-negative weights a self-loop never helps a shortest path, so most algorithms ignore it.
Negative weights
Weights can be negative, for example a trade that earns money instead of costing it. This is the case where the choice of algorithm matters. Dijkstra's algorithm assumes that a vertex's distance is final once it is taken from the priority queue, and a negative edge later in the path can break that assumption. For graphs with negative weights, use the Bellman-Ford algorithm. It is outside this tutorial.
Direction matters here. In an undirected graph a single negative edge is already a negative cycle, because you can cross it back and forth and lower the total each time. Negative weights are therefore only practical in directed graphs.
Floating-point weights
Weights like 0.1 and 0.2 are stored inexactly, so sums such as 0.1 + 0.2 produce 0.30000000000000004. Comparing path totals with == can then fail. Where you can, store weights as integers in a small unit (cents, meters, milliseconds). Otherwise compare with math.isclose.
Choosing a weight that matches the question
The algorithm minimizes whatever the weights say. If you want the most reliable route and store failure probabilities as weights, you will get the least failure-prone path only if the numbers are combined by addition the way the algorithm expects. Probabilities multiply, so people usually store -log(p) to turn products into sums. Before running an algorithm, check that a path's total, computed by adding weights, is the quantity you want minimized.
Summary of decisions
- Use an unweighted graph when only the existence of a link matters, or when every link costs the same.
- Use a weighted graph when links differ in cost, distance, capacity, or strength.
- Make the graph directed if the weight of A to B can differ from B to A, or if the relationship is not symmetric.
- Check for negative weights before choosing a shortest-path algorithm.
Exercise
A directed weighted graph is built with addedge(g, "P", "Q", 3, directed=True) and addedge(g, "Q", "P", 5, directed=True). What do g["P"]["Q"] and g["Q"]["P"] return, and what would they return if directed=True were left out of both calls?
Show answer
With directed=True, g["P"]["Q"] is 3 and g["Q"]["P"] is 5, because the two directions are separate edges. Without it, the first call stores 3 in both directions, and the second call then overwrites both with 5. Both lookups return 5, and the weight 3 is lost.
Exercise
Using the weighted graph from this chapter, what is the weight of the path ["B", "A", "C"], and why does if graph[u].get(v): give wrong results for an edge with weight 0?
Show answer
The path weight is 4 + 1 = 5, from edge B to A (weight 4) and edge A to C (weight 1). The expression graph[u].get(v) returns 0 for a zero-weight edge, and 0 is falsy in Python, so the test treats an existing edge as missing. The correct test is v in graph[u].