How to Implement Graph in Python: Simple Guide with Examples
To implement a graph in Python, use a
dictionary where keys are nodes and values are lists of connected nodes (adjacency list). This structure allows easy addition and traversal of nodes and edges.Syntax
A graph can be represented as an adjacency list using a dictionary where each key is a node and its value is a list of connected nodes (neighbors).
Example syntax:
graph = {}- creates an empty graphgraph[node] = [neighbors]- assigns neighbors to a nodegraph[node].append(neighbor)- adds a neighbor to a node
python
graph = {}
graph['A'] = ['B', 'C']
graph['B'] = ['A', 'D']
graph['C'] = ['A']
graph['D'] = ['B']Example
This example shows how to create a simple undirected graph and print its adjacency list.
python
graph = {}
def add_edge(graph, node1, node2):
if node1 not in graph:
graph[node1] = []
if node2 not in graph:
graph[node2] = []
graph[node1].append(node2)
graph[node2].append(node1) # For undirected graph
add_edge(graph, 'A', 'B')
add_edge(graph, 'A', 'C')
add_edge(graph, 'B', 'D')
print('Graph adjacency list:')
for node in graph:
print(f'{node}: {graph[node]}')Output
Graph adjacency list:
A: ['B', 'C']
B: ['A', 'D']
C: ['A']
D: ['B']
Common Pitfalls
Common mistakes when implementing graphs include:
- Forgetting to add both directions in an undirected graph, which causes incomplete connections.
- Not initializing the adjacency list for new nodes before appending neighbors.
- Using mutable default arguments or shared lists that cause unexpected behavior.
python
graph = {}
def add_edge_wrong(graph, node1, node2):
# Missing initialization of adjacency lists
graph[node1].append(node2) # This will cause KeyError if node1 not in graph
# Correct way:
def add_edge_right(graph, node1, node2):
if node1 not in graph:
graph[node1] = []
if node2 not in graph:
graph[node2] = []
graph[node1].append(node2)
graph[node2].append(node1)Quick Reference
Tips for implementing graphs in Python:
- Use a dictionary with lists for adjacency representation.
- Initialize nodes before adding edges.
- For undirected graphs, add edges in both directions.
- Use functions to add edges to keep code clean.
Key Takeaways
Use a dictionary of lists to represent a graph as an adjacency list in Python.
Always initialize nodes in the graph before adding neighbors to avoid errors.
For undirected graphs, add edges in both directions to represent connections correctly.
Encapsulate edge addition in functions to avoid repetitive code and mistakes.