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.

Easy Python 3.9+ Aug 9, 2026 OOP & classes 12 views 0 copies

Python code

42 lines
Python 3.9+
class 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

stdout
{'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

  1. Use a set instead of a list for adjacency to avoid duplicate entries
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from OOP & classes

Related tutorials and quizzes for this topic.