PYTHON
Representing Graphs with Adjacency Lists in Python
Master how to represent graph data structures using Python dictionaries and sets (adjacency lists), essential for modeling relationships like social networks, routing, or content dependencies in web backends.
def create_graph():
graph = {
'A': {'B', 'C'},
'B': {'A', 'D', 'E'},
'C': {'A', 'F'},
'D': {'B'},
'E': {'B', 'F'},
'F': {'C', 'E'}
}
return graph
def add_edge(graph, u, v):
# Add edge u -> v
if u not in graph:
graph[u] = set()
graph[u].add(v)
# For an undirected graph, add v -> u as well
if v not in graph:
graph[v] = set()
graph[v].add(u)
print(f"Added edge {u}-{v}. Graph: {graph}")
def get_neighbors(graph, node):
return graph.get(node, set())
# Example Usage
my_graph = create_graph()
print(f"Initial Graph: {my_graph}")
add_edge(my_graph, 'A', 'G')
print(f"Neighbors of B: {get_neighbors(my_graph, 'B')}")
print(f"Neighbors of G: {get_neighbors(my_graph, 'G')}")
How it works: This snippet demonstrates representing a graph using an adjacency list, where each key in the dictionary is a node, and its value is a set of connected nodes. This structure is highly efficient for sparse graphs (graphs with relatively few edges) and allows for quick retrieval of all neighbors of a given node (O(degree)). It's commonly used in web applications for managing relationships (e.g., "friends of friends"), sitemap generation, or complex permission systems.