Graph as dict
A graph as a dict is an adjacency list stored in a dictionary: each key is a node, each value is the collection of neighbours. It is the usual Python representation for BFS, DFS, and shortest paths.
Detailed Explanation
You do not need a Graph class to solve most interview and application graph problems. A dict of lists (or sets) is enough. {"a": ["b", "c"], "b": ["d"], "c": [], "d": []} is a directed graph. An undirected edge appears twice, once in each list. A weighted graph stores pairs: {"a": [("b", 3), ("c", 1)]}.
defaultdict(list) or defaultdict(set) lets you add edges without pre-creating nodes. After building, convert to a plain dict if you want missing-node access to raise. Keep isolated nodes as keys with empty lists; otherwise you will drop them from graph.keys() and skip them in a full traversal.
Sets as neighbour collections make "is there an edge?" O(1) and ignore duplicate edges. Lists preserve insertion order and allow parallel edges. Choose lists unless you need membership tests.
Traversal code stays generic: for nxt in graph[node]. BFS uses a deque and a seen set. DFS uses a stack or recursion. You must mark seen nodes on a graph with cycles, or you loop forever. Weighted shortest paths use heapq (Dijkstra) or dynamic programming (DAGs).
This representation is adjacency lists. An adjacency matrix is a nested list or a dict of dicts of booleans. Matrices win on dense graphs and lose on sparse ones. Most real graphs are sparse; most Python solutions use a dict of lists.
Objects as nodes are fine if they are hashable. If they are not, give them ids and store the objects in a second dict. Do not put unhashable lists in as keys.
Code Examples
from collections import defaultdict
edges = [("a", "b"), ("a", "c"), ("b", "d")]
graph: dict[str, list[str]] = defaultdict(list)
for src, dst in edges:
graph[src].append(dst)
graph.setdefault(dst, []) # keep isolated-looking endpoints
print(dict(graph))
# {'a': ['b', 'c'], 'b': ['d'], 'c': [], 'd': []}# Undirected: store both directions.
def add_undirected(graph: dict, a: str, b: str) -> None:
graph.setdefault(a, []).append(b)
graph.setdefault(b, []).append(a)# Weighted neighbours as (node, cost) pairs.
roads = {"home": [("shop", 4), ("station", 2)], "shop": [], "station": []}
print(roads["home"][1]) # ('station', 2)Common Gotchas
Forgetting the reverse edge on an undirected graph
BFS then cannot walk back, and "connected" is wrong.
No `seen` set on a cyclic graph
DFS and BFS never finish. Mark a node when you first enqueue or recurse.
Isolated nodes disappear if you only insert sources
add `setdefault(dst, [])` or initialise every node.
`defaultdict` inserts on read
`graph["missing"]` while debugging creates a node. Use `in` or `get`.