Calculating Weighted Shortest Paths in NetworkX
Learn how to implement weighted shortest paths in NetworkX using Dijkstra and Bellman-Ford algorithms, including how to handle negative weights and avoid common attribute pitfalls.
12 Jan 2026, 23:32 UTC

Solving for Cost-Based Routing
When calculating the shortest path in a network, the "shortest" route is rarely the one with the fewest hops; it is typically the one with the lowest cumulative cost, such as distance, latency, or financial expense. In NetworkX, this is achieved by assigning a weight attribute to edges and specifying that attribute during the path search.
The primary takeaway is that nx.shortest_path and nx.shortest_path_length look for an edge attribute named weight by default. If you provide a graph where edges have this attribute, the library calculates the path based on the sum of those values rather than the number of edges.
Implementing Weighted Paths
To implement weighted routing, you must define the weight during edge creation or via an update. NetworkX uses Dijkstra's algorithm by default for non-negative weights, which is computationally efficient for most production use cases.
import networkx as nx
# Initialize a Directed Graph (DiGraph)
# Use nx.Graph() if the edges are bidirectional
G = nx.DiGraph()
# Add edges with a 'weight' attribute
# Path A -> C directly costs 10
# Path A -> B -> C costs 2 + 3 = 5
G.add_edge('A', 'B', weight=2)
G.add_edge('B', 'C', weight=3)
G.add_edge('A', 'C', weight=10)
# Calculate the path using the default 'weight' attribute
path = nx.shortest_path(G, source='A', target='C', weight='weight')
length = nx.shortest_path_length(G, source='A', target='C', weight='weight')
print(f"Path: {path}") # Expected: ['A', 'B', 'C']
print(f"Total Cost: {length}") # Expected: 5
Algorithm Selection: Dijkstra vs. Bellman-Ford
The choice of algorithm depends entirely on whether your weights can be negative. Using the wrong algorithm can lead to incorrect paths or infinite loops.
| Scenario | Recommended Method | NetworkX Implementation | Behavior |
|---|---|---|---|
| All weights ≥ 0 | Dijkstra | method='dijkstra' |
Fastest; guaranteed optimal for non-negative edges. |
| Some weights < 0 | Bellman-Ford | method='bellman-ford' |
Slower; handles negative edges; detects negative cycles. |
If your data includes negative weights, you must explicitly set the method. For example: nx.shortest_path(G, source, target, weight='weight', method='bellman-ford'). If a negative cycle exists (a loop where the total weight is less than zero), Bellman-Ford will raise a NetworkXUnbounded exception, as a "shortest" path technically does not exist (you could loop infinitely to reduce the cost).
Common Implementation Pitfalls
The "Missing Weight" Silent Failure
One of the most frequent errors is omitting the weight attribute on some edges. If NetworkX encounters an edge missing the specified weight attribute, it defaults that specific edge's cost to 1. This can lead to logically incorrect paths that are difficult to debug because the code does not throw an error.
Verification Step: To check if your graph is consistently weighted, you can validate the edges before running the pathfinder:
# Check for edges missing the 'weight' key
missing = [e for e in G.edges(data=True) if 'weight' not in e[2]]
if missing:
print(f"Warning: {len(missing)} edges are missing weight attributes.")
Ignoring Weights Entirely
If you wish to find the path with the fewest hops regardless of the weight attribute, you must explicitly pass weight=None. If you omit the weight parameter entirely in some versions or contexts, the behavior may default to the attribute named "weight" if it exists.
Performance and Limitations
- Graph Density: For very large, dense graphs, repeated calls to
shortest_pathfor different targets from the same source are inefficient. Usenx.single_source_dijkstrato get all shortest paths from one node in a single pass. - Custom Weight Functions: Instead of a string (
'weight'), you can pass a function to theweightparameter. This function must take an edge as input and return a numeric value. If the function returnsNoneor a non-numeric type, the algorithm will fail or produce unstable results. - Directedness: In a
DiGraph, paths are one-way. If you need to find the shortest path regardless of direction, ensure you usenx.Graph()or add edges in both directions.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.