PYTHON

Modeling Graph Data with Adjacency Lists

Represent graph-like data structures, such as website navigation or social connections, using a dictionary-based adjacency list for efficient traversal and management.

from typing import Dict, List, Set

# Representing a simple website navigation graph
# Key: page, Value: set of pages reachable from key
website_navigation: Dict[str, Set[str]] = {
    "Home": {"About", "Products", "Contact"},
    "About": {"Home", "Team"},
    "Products": {"Home", "CategoryA", "CategoryB"},
    "CategoryA": {"Products"},
    "CategoryB": {"Products", "Item1", "Item2"},
    "Contact": {"Home"},
    "Team": {"About"},
    "Item1": {"CategoryB"},
    "Item2": {"CategoryB"}
}

# Representing a social network (undirected graph)
social_network: Dict[str, Set[str]] = {
    "Alice": {"Bob", "Charlie"},
    "Bob": {"Alice", "David"},
    "Charlie": {"Alice", "Eve"},
    "David": {"Bob"},
    "Eve": {"Charlie"}
}

def get_reachable_pages(graph: Dict[str, Set[str]], start_page: str) -> Set[str]:
    visited = set()
    queue = [start_page]
    while queue:
        page = queue.pop(0) # Breadth-First Search (BFS)
        if page not in visited:
            visited.add(page)
            for neighbor in graph.get(page, set()):
                if neighbor not in visited:
                    queue.append(neighbor)
    return visited

def are_friends(network: Dict[str, Set[str]], person1: str, person2: str) -> bool:
    return person2 in network.get(person1, set())

print("--- Website Navigation Analysis ---")
print(f"Pages reachable from 'Home': {get_reachable_pages(website_navigation, 'Home')}")
print(f"Pages reachable from 'CategoryA': {get_reachable_pages(website_navigation, 'CategoryA')}")
print("-" * 30)

print("--- Social Network Analysis ---")
print(f"Are Alice and Bob friends? {are_friends(social_network, 'Alice', 'Bob')}")
print(f"Are David and Eve friends? {are_friends(social_network, 'David', 'Eve')}")
print(f"Alice's friends: {social_network.get('Alice')}")
print("-" * 30)
How it works: An adjacency list, typically implemented using a dictionary where keys are nodes and values are lists or sets of connected nodes, is an effective way to represent graph data structures in Python. This snippet demonstrates its use for modeling website navigation paths or social network connections. It allows for efficient traversal (e.g., finding all reachable pages using a simple BFS) and querying relationships, which is fundamental for features like sitemaps, recommendation engines, or social features in web applications. Using `set` for neighbors ensures uniqueness and efficient membership testing.

Need help integrating this into your project?

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

Hire DigitalCodeLabs