PYTHON

Represent Graphs with Adjacency Lists in Python

Learn how to model graph data structures using dictionaries to create adjacency lists in Python, enabling efficient representation and traversal of relationships between entities in web applications.

# Representing an undirected graph using an adjacency list
# Key: node, Value: list of connected nodes
graph = {
    'A': ['B', 'C'],
    'B': ['A', 'D', 'E'],
    'C': ['A', 'F'],
    'D': ['B'],
    'E': ['B', 'F'],
    'F': ['C', 'E']
}

print("Graph Adjacency List:")
for node, neighbors in graph.items():
    print(f"  {node}: {neighbors}")

# Example: Check if two nodes are connected
def are_connected(graph, node1, node2):
    return node2 in graph.get(node1, []) or node1 in graph.get(node2, [])

print(f"
Is A connected to B? {are_connected(graph, 'A', 'B')}")
print(f"Is D connected to C? {are_connected(graph, 'D', 'C')}")

# Example: Add a new connection
def add_edge(graph, node1, node2):
    if node1 not in graph:
        graph[node1] = []
    if node2 not in graph:
        graph[node2] = []
    if node2 not in graph[node1]:
        graph[node1].append(node2)
    if node1 not in graph[node2]:
        graph[node2].append(node1) # For undirected graph
    print(f"Added edge between {node1} and {node2}")

add_edge(graph, 'D', 'F')
print(f"
Updated graph after adding edge D-F:")
for node, neighbors in graph.items():
    print(f"  {node}: {neighbors}")
How it works: Graphs are powerful data structures for modeling relationships, common in social networks, recommendation engines, and navigation systems. This snippet demonstrates representing an undirected graph using an adjacency list, where each key in the dictionary is a node, and its value is a list of nodes it's connected to. This representation allows for efficient addition of edges and checking for connections between nodes, making it suitable for many web-related applications.

Need help integrating this into your project?

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

Hire DigitalCodeLabs