PYTHON

Representing Graphs with Adjacency Lists

Learn to represent graph data structures using Python dictionaries and lists, ideal for modeling social networks, website navigation, or dependency graphs in web applications.

from collections import defaultdict

# --- Undirected Graph Representation ---
def create_undirected_graph(edges):
    graph = defaultdict(list)
    for u, v in edges:
        graph[u].append(v)
        graph[v].append(u) # Add edge in both directions for undirected
    return graph

# Example: Social network (users are nodes, friendships are edges)
social_network_edges = [('Alice', 'Bob'), ('Bob', 'Charlie'), ('Alice', 'David'), ('David', 'Eve')]
social_graph = create_undirected_graph(social_network_edges)

print("
--- Undirected Social Network ---")
for node, neighbors in social_graph.items():
    print(f"{node}: {neighbors}")
# Expected Output:
# Alice: ['Bob', 'David']
# Bob: ['Alice', 'Charlie']
# Charlie: ['Bob']
# David: ['Alice', 'Eve']
# Eve: ['David']

# --- Directed Graph Representation ---
def create_directed_graph(edges):
    graph = defaultdict(list)
    for u, v in edges:
        graph[u].append(v) # Only add edge from u to v
    return graph

# Example: Website navigation (pages are nodes, links are edges)
website_links = [('Home', 'About'), ('Home', 'Products'), ('About', 'Contact'), ('Products', 'Item1'), ('Item1', 'Home')]
website_graph = create_directed_graph(website_links)

print("
--- Directed Website Navigation ---")
for node, neighbors in website_graph.items():
    print(f"{node}: {neighbors}")
# Expected Output:
# Home: ['About', 'Products']
# About: ['Contact']
# Products: ['Item1']
# Item1: ['Home']
# Contact: [] (Contact might not appear if it has no outgoing links and isn't an 'origin' node in any edge)

# Function to find neighbors of a node
def get_neighbors(graph, node):
    return graph.get(node, [])

print(f"
Neighbors of 'Alice' in social network: {get_neighbors(social_graph, 'Alice')}")
print(f"Neighbors of 'Home' in website navigation: {get_neighbors(website_graph, 'Home')}")
How it works: Graphs are powerful data structures representing relationships between entities (nodes/vertices) via connections (edges). In Python, an adjacency list is a common and efficient way to represent a graph using a dictionary. Each key in the dictionary is a node, and its corresponding value is a list (or set) of its adjacent nodes. This snippet demonstrates how to build both undirected (e.g., social networks where friendship is mutual) and directed (e.g., website navigation where links are one-way) graphs. This pattern is fundamental for various web development tasks, from recommendation systems and social features to routing algorithms and sitemap generation.

Need help integrating this into your project?

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

Hire DigitalCodeLabs