Generate a graph using Dictionary in Python

Graphs can be implemented using Dictionary in Python where each key represents a vertex and its value contains a list of connected vertices. This creates an adjacency list representation of a graph G(V, E).

We'll use Python's defaultdict from the collections module, which provides additional features over regular dictionaries by automatically creating missing keys with default values.

Graph Representation

Consider this undirected graph with 6 vertices (A, B, C, D, E, F) and 8 edges ?

A B C D E F

Creating a Graph from Dictionary

Here's how to create and represent the graph using a dictionary ?

from collections import defaultdict

def create_graph():
    graph = defaultdict(list)
    
    # Add vertices and their connections
    graph['A'] = ['B', 'C']
    graph['B'] = ['A', 'D', 'E']
    graph['C'] = ['A', 'E']
    graph['D'] = ['B', 'E', 'F']
    graph['E'] = ['B', 'C', 'D', 'F']
    graph['F'] = ['D', 'E']
    
    return graph

# Create and display the graph
my_graph = create_graph()
for node in my_graph.keys():
    print(f"{node}: {my_graph[node]}")
A: ['B', 'C']
B: ['A', 'D', 'E']
C: ['A', 'E']
D: ['B', 'E', 'F']
E: ['B', 'C', 'D', 'F']
F: ['D', 'E']

Finding a Path Between Vertices

We can find a path from source to destination using recursive depth-first search ?

from collections import defaultdict

def create_graph():
    graph = defaultdict(list)
    graph['A'] = ['B', 'C']
    graph['B'] = ['A', 'D', 'E']
    graph['C'] = ['A', 'E']
    graph['D'] = ['B', 'E', 'F']
    graph['E'] = ['B', 'C', 'D', 'F']
    graph['F'] = ['D', 'E']
    return graph

def get_path(graph, src, dest, path=[]):
    path = path + [src]
    if src == dest:
        return path
    
    for vertex in graph[src]:
        if vertex not in path:
            new_path = get_path(graph, vertex, dest, path)
            if new_path:
                return new_path
    return None

my_graph = create_graph()
path = get_path(my_graph, 'A', 'F')
print(f"Path from A to F: {path}")
Path from A to F: ['A', 'B', 'D', 'F']

Finding All Possible Paths

To find all paths between two vertices, we modify our approach to collect all valid paths ?

from collections import defaultdict

def create_graph():
    graph = defaultdict(list)
    graph['A'] = ['B', 'C']
    graph['B'] = ['A', 'D', 'E']
    graph['C'] = ['A', 'E']
    graph['D'] = ['B', 'E', 'F']
    graph['E'] = ['B', 'C', 'D', 'F']
    graph['F'] = ['D', 'E']
    return graph

def get_all_paths(graph, src, dest, path=[]):
    path = path + [src]
    if src == dest:
        return [path]
    
    paths = []
    for vertex in graph[src]:
        if vertex not in path:
            new_paths = get_all_paths(graph, vertex, dest, path)
            paths.extend(new_paths)
    return paths

my_graph = create_graph()
all_paths = get_all_paths(my_graph, 'A', 'F')
print("All paths from A to F:")
for i, path in enumerate(all_paths, 1):
    print(f"{i}. {path}")
All paths from A to F:
1. ['A', 'B', 'D', 'F']
2. ['A', 'B', 'D', 'E', 'F']
3. ['A', 'B', 'E', 'D', 'F']
4. ['A', 'B', 'E', 'F']
5. ['A', 'C', 'E', 'B', 'D', 'F']
6. ['A', 'C', 'E', 'D', 'B', 'F']
7. ['A', 'C', 'E', 'D', 'F']
8. ['A', 'C', 'E', 'F']

Finding the Shortest Path

To find the shortest path, we compare path lengths and keep track of the minimum ?

from collections import defaultdict

def create_graph():
    graph = defaultdict(list)
    graph['A'] = ['B', 'C']
    graph['B'] = ['A', 'D', 'E']
    graph['C'] = ['A', 'E']
    graph['D'] = ['B', 'E', 'F']
    graph['E'] = ['B', 'C', 'D', 'F']
    graph['F'] = ['D', 'E']
    return graph

def get_shortest_path(graph, src, dest, path=[]):
    path = path + [src]
    if src == dest:
        return path
    
    shortest = None
    for vertex in graph[src]:
        if vertex not in path:
            new_path = get_shortest_path(graph, vertex, dest, path)
            if new_path:
                if not shortest or len(new_path) < len(shortest):
                    shortest = new_path
    return shortest

my_graph = create_graph()
shortest_path = get_shortest_path(my_graph, 'A', 'F')
print(f"Shortest path from A to F: {shortest_path}")
print(f"Path length: {len(shortest_path)}")
Shortest path from A to F: ['A', 'B', 'D', 'F']
Path length: 4

Conclusion

Using dictionaries to represent graphs in Python provides an efficient adjacency list implementation. This approach allows easy traversal and path-finding operations using recursive algorithms for various graph problems.

Updated on: 2026-03-25T05:06:37+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements