PYTHON

Efficient Graph Representation with Adjacency Lists

Learn to represent graphs using dictionaries and lists for efficient traversal, shortest path algorithms, and network modeling in Python web applications.

class Graph:
    def __init__(self):
        self.adj_list = {}

    def add_node(self, node):
        if node not in self.adj_list:
            self.adj_list[node] = []

    def add_edge(self, node1, node2, bidirection=True):
        self.add_node(node1)
        self.add_node(node2)
        self.adj_list[node1].append(node2)
        if bidirection:
            self.adj_list[node2].append(node1)

    def get_neighbors(self, node):
        return self.adj_list.get(node, [])

    def __str__(self):
        graph_str = ""
        for node, neighbors in self.adj_list.items():
            graph_str += f"{node}: {', '.join(map(str, neighbors))}
"
        return graph_str

# Example Usage:
my_graph = Graph()
my_graph.add_edge('A', 'B')
my_graph.add_edge('A', 'C')
my_graph.add_edge('B', 'D')
my_graph.add_edge('C', 'E')
my_graph.add_edge('D', 'E')

print(my_graph)
# Output:
# A: B, C
# B: A, D
# C: A, E
# D: B, E
# E: C, D

print(f"Neighbors of B: {my_graph.get_neighbors('B')}") # Output: Neighbors of B: ['A', 'D']
How it works: This snippet demonstrates how to represent a graph using an adjacency list, which is a dictionary where each key is a node and its value is a list of nodes directly connected to it. This structure is highly efficient for sparse graphs (graphs with relatively few edges) and is commonly used in algorithms like Breadth-First Search (BFS) or Depth-First Search (DFS), critical for social network features, recommendation engines, or mapping services in web applications. The `Graph` class provides methods to add nodes, add edges (unidirectional or bidirectional), and retrieve neighbors of a given node.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs