Dijkstra Shortest Path With Min Heap (Python)

Compute single source shortest paths in a weighted graph using Dijkstra with heapq for efficient extraction.

PythonData Fetching

Code

pythonsnippet
17 lines
import heapq


def dijkstra(graph, start):
    dist = {n: float("inf") for n in graph}
    dist[start] = 0
    heap = [(0, start)]
    while heap:
        d, node = heapq.heappop(heap)
        if d > dist[node]:
            continue
        for neighbor, weight in graph.get(node, []):
            nd = d + weight
            if nd < dist[neighbor]:
                dist[neighbor] = nd
                heapq.heappush(heap, (nd, neighbor))
    return dist

What the code does

Dijkstra Shortest Path With Min Heap (Python) is built around the function dijkstra.

Iteration happens inside while heap — everything outside it runs once.

Points of care

  • heapq must be installed first — the snippet imports it directly.

Applying it

Entry signature: def dijkstra(graph, start)

dijkstra is what another module would consume; nothing else here is load-bearing for callers.

Interactive Tools for This Topic

FAQ

Which packages does this snippet need?
None. Every symbol the code uses resolves inside the standard library. The file defines `dijkstra` at load time.