← Back to all snippets
PYTHON

Representing Graphs with Adjacency Lists in Python Dictionaries

Learn to model graph data structures using Python dictionaries to represent nodes and their connections as adjacency lists, foundational for graph algorithms.

# Representing an undirected graph using an adjacency list (dictionary of lists)
graph = {
    'A': ['B', 'C'],
    'B': ['A', 'D', 'E'],
    'C': ['A', 'F'],
    'D': ['B'],
    'E': ['B', 'F'],
    'F': ['C', 'E']
}

def add_edge(g, u, v):
    """Adds an undirected edge between nodes u and v."""
    if u not in g:
        g[u] = []
    if v not in g:
        g[v] = []
    g[u].append(v)
    g[v].append(u)

def print_graph(g):
    for node, neighbors in g.items():
        print(f"{node}: {', '.join(neighbors)}")

print("Initial Graph:")
print_graph(graph)

# Adding a new node and edge
add_edge(graph, 'G', 'A')
print("
Graph after adding edge 'G-A':")
print_graph(graph)

# Checking for connectivity
print(f"
Neighbors of B: {graph['B']}")
print(f"Is A connected to D? {'D' in graph['A']}")
print(f"Is A connected to B? {'B' in graph['A']}")

# A simple depth-first search (DFS) traversal example
def dfs(g, start_node, visited=None):
    if visited is None:
        visited = set()
    visited.add(start_node)
    print(start_node, end=" ")
    for neighbor in g.get(start_node, []):
        if neighbor not in visited:
            dfs(g, neighbor, visited)

print("
DFS traversal from 'A':")
dfs(graph, 'A')
print()
How it works: Graphs are versatile data structures used to model relationships between entities (nodes/vertices) via connections (edges). An adjacency list, often implemented using a Python dictionary where keys are nodes and values are lists of their neighbors, is an efficient way to represent sparse graphs. This structure facilitates common graph algorithms like traversal (e.g., DFS, BFS) and shortest path calculations, useful for social networks or routing.

Need help integrating this into your project?

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

Hire DigitalCodeLabs