Sub topic 8
Storing a graph as an adjacency list
This chapter assumes you can use Python dictionaries and sets, read basic big-O notation, and already know the difference between undirected, directed, and weighted graphs. Here you will learn the most common way to store a graph in memory.
The idea
An adjacency list stores, for each vertex, the vertices it connects to. Each vertex has its own small collection of neighbors, so the memory used grows with the number of vertices plus the number of edges. Written as O(V + E), this suits sparse graphs, where most possible edges are absent.
In Python, a dictionary of dictionaries works well:
- The outer keys are vertices.
- The inner keys are neighbors.
- The inner values are edge weights, with 1 as the default for unweighted graphs.
One function for all three graph types
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
undirected = {}
add_edge(undirected, "A", "B")
add_edge(undirected, "B", "C")
directed = {}
add_edge(directed, "A", "B", directed=True)
add_edge(directed, "B", "C", directed=True)
weighted = {}
add_edge(weighted, "A", "B", 4)
add_edge(weighted, "A", "C", 1)
add_edge(weighted, "C", "B", 2)
print(undirected) # {'A': {'B': 1}, 'B': {'A': 1, 'C': 1}, 'C': {'B': 1}}
print(directed) # {'A': {'B': 1}, 'B': {'C': 1}, 'C': {}}The line graph.setdefault(v, {}) makes sure the target vertex exists even when it has no outgoing edges. Without it, C would be missing from directed, and later code that does graph[u] would raise a KeyError.
An undirected edge is stored twice, once under each endpoint. A directed edge is stored once, under its source.
Common operations
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
def neighbors(graph, u):
return list(graph[u])
def has_edge(graph, u, v):
return v in graph[u]
def weight_of(graph, u, v):
return graph[u][v]
weighted = {}
add_edge(weighted, "A", "B", 4)
add_edge(weighted, "A", "C", 1)
add_edge(weighted, "C", "B", 2)
print(neighbors(weighted, "A")) # ['B', 'C']
print(has_edge(weighted, "B", "C")) # True
print(weight_of(weighted, "C", "B")) # 2
print(sum(len(n) for n in weighted.values()) // 2) # 3 edgesThe edge count divides by 2 only because every edge in this graph is stored twice. For a directed graph, skip the division.
| Operation | Cost with a dict of dicts |
|---|---|
| List the neighbors of u | O(deg(u)) |
| Check whether edge (u, v) exists | O(1) on average |
| Read the weight of (u, v) | O(1) on average |
| Out-degree of u | O(1) |
| In-degree of u (directed) | O(V + E), a full scan |
| Total space | O(V + E) |
The expensive entry is in-degree. The structure is organized by source, so finding who points at a vertex means checking every list. If you need that often, store a second, reversed graph.
Gotchas
- A self-loop
add_edge(g, "A", "A")is stored once, because both writes hit the same key. The "sum of list lengths divided by 2" edge count is then off by one half for that edge. - If you use inner lists instead of dictionaries,
has_edgebecomes O(deg(u)). Dictionaries or sets keep it fast. - Mutating a graph while iterating over it raises a
RuntimeError. Collect changes first, then apply them.
Exercise
A directed graph has 1,000 vertices and 3,000 edges, stored as a dict of dicts. Roughly how many inner-dictionary entries exist in total, and what does it cost to find the in-degree of one vertex?
Show answer
There are 3,000 entries, because a directed edge is stored once, under its source. Finding one vertex's in-degree means checking every vertex's neighbors, which is O(V + E), about 4,000 steps here.