PYTHON
Represent Graphs as Adjacency Lists Using Python Dictionaries
Learn to model graph data structures, like social networks or dependencies, using Python dictionaries to create an adjacency list representation for nodes and edges.
# Represent a graph using an adjacency list (dictionary of lists)
# Keys are nodes, values are lists of connected nodes (neighbors)
graph = {
"A": ["B", "C"],
"B": ["A", "D", "E"],
"C": ["A", "F"],
"D": ["B"],
"E": ["B", "F"],
"F": ["C", "E"],
"G": [] # Node G has no connections
}
print("Graph Adjacency List:")
for node, neighbors in graph.items():
print(f"{node}: {neighbors}")
# Check if a node exists and its neighbors
node_to_check = "B"
if node_to_check in graph:
print(f"
Neighbors of {node_to_check}: {graph[node_to_check]}")
else:
print(f"
Node {node_to_check} not found.")
# Adding a new edge (e.g., from A to D)
if "D" not in graph["A"]:
graph["A"].append("D")
if "A" not in graph["D"]:
graph["D"].append("A") # For an undirected graph, add reverse edge too
print(f"
Graph after adding edge A-D: {graph}")
How it works: This snippet illustrates how to represent a graph data structure using an adjacency list implemented with Python dictionaries. Each key in the dictionary represents a node, and its corresponding value is a list of other nodes it is connected to (its neighbors). This is a flexible and efficient way to model relationships, common in web applications for features like friend networks, content recommendation systems, or dependency tracking.