PYTHON

Implement a Basic Graph using Adjacency List

Learn to represent graph data structures using Python dictionaries and lists, creating an adjacency list model useful for modeling networks, social connections, or map routes.

# Representing a 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"]
}

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

# Example operations:
# Add a new node
graph["G"] = []

# Add an edge
def add_edge(graph, u, v):
    if u not in graph:
        graph[u] = []
    if v not in graph:
        graph[v] = []
    if v not in graph[u]:
        graph[u].append(v)
    if u not in graph[v]: # For undirected graph
        graph[v].append(u)

add_edge(graph, "A", "G")
add_edge(graph, "G", "D")

print("
Graph after adding nodes and edges:")
for node, neighbors in graph.items():
    print(f"{node}: {', '.join(neighbors)}")

# Expected output structure:
# Graph Adjacency List:
# A: B, C
# B: A, D, E
# C: A, F
# D: B
# E: B, F
# F: C, E
#
# Graph after adding nodes and edges:
# A: B, C, G
# B: A, D, E
# C: A, F
# D: B, G
# E: B, F
# F: C, E
# G: A, D
How it works: This snippet demonstrates how to implement a basic graph data structure using Python dictionaries and lists, specifically an adjacency list representation. Each key in the dictionary represents a node in the graph, and its corresponding value is a list of nodes that are directly connected to it (its neighbors). This method is memory-efficient for sparse graphs and allows for easy addition of nodes and edges, making it suitable for representing relationships and networks.

Need help integrating this into your project?

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

Hire DigitalCodeLabs