Graph Class with Adjacency Dict in Python
Build an undirected graph class using a dictionary of adjacency lists with methods to add vertices, edges, remove edges, and query neighbors.
Python code
42 linesclass Graph:
def __init__(self):
self.adjacency = {}
def add_vertex(self, vertex):
if vertex not in self.adjacency:
self.adjacency[vertex] = []
def add_edge(self, u, v):
self.add_vertex(u)
self.add_vertex(v)
self.adjacency[u].append(v)
self.adjacency[v].append(u)
def remove_edge(self, u, v):
if u in self.adjacency and v in self.adjacency:
if v in self.adjacency[u]:
self.adjacency[u].remove(v)
if u in self.adjacency[v]:
self.adjacency[v].remove(u)
def has_edge(self, u, v):
return u in self.adjacency and v in self.adjacency[u]
def neighbors(self, vertex):
return self.adjacency.get(vertex, [])
def __str__(self):
return str(self.adjacency)
if __name__ == "__main__":
g = Graph()
g.add_edge("A", "B")
g.add_edge("A", "C")
g.add_edge("B", "C")
print(g)
print(f"Has A-B edge: {g.has_edge('A', 'B')}")
print(f"Neighbors of A: {g.neighbors('A')}")
g.remove_edge("A", "B")
print(f"After removing A-B: {g}")
print(f"Has A-B edge: {g.has_edge('A', 'B')}")
Output
{'A': ['B', 'C'], 'B': ['A', 'C'], 'C': ['A', 'B']}
Has A-B edge: True
Neighbors of A: ['B', 'C']
After removing A-B: {'A': ['C'], 'B': ['C'], 'C': ['A', 'B']}
Has A-B edge: False
How it works
This graph stores each vertex as a key in a dictionary, with the value being a list of adjacent vertices. Adding an edge calls add_vertex for both endpoints so every node always has a list. Removing an edge checks both adjacency lists and removes the counterpart pointers, keeping the undirected structure consistent. The has_edge and neighbors methods safely check membership, returning an empty list for missing vertices.
Common mistakes
- Forgetting to add missing vertices before appending to their adjacency lists
- Removing edges only from one side of an undirected graph
- Assuming a vertex exists when calling `neighbors`, leading to KeyError
Variations
- Use a set instead of a list for adjacency to avoid duplicate entries
- Store edge weights by using a nested dictionary or list of tuples
Real-world use cases
- Modeling social networks where users are vertices and friendships are edges in a recommendation engine.
- Representing road networks or flight routes for shortest-path algorithms like Dijkstra's.
- Building dependency graphs in build systems to detect cycles and order tasks.
Sponsored
More from OOP & classes
- Add property getter setter validation in Python easy
- Binary Tree Inorder Traversal in Python easy
- Borg pattern shared state in Python medium
- Bridge Pattern in Python: Separate Abstraction from Implementation medium
- Composable Predicates with the &, |, ~ Operators in Python medium
- Composition over Inheritance: How to Build a Wallet Account in Python easy
Keep learning
Related tutorials and quizzes for this topic.