Building an undirected graph and finding shortest path using Dictionaries in Python Last Updated : 15 Dec, 2021 Comments Improve Suggest changes Like Article Like Report Prerequisites: BFS for a GraphDictionaries in Python In this article, we will be looking at how to build an undirected graph and then find the shortest path between two nodes/vertex of that graph easily using dictionaries in Python Language. Building a Graph using Dictionaries Approach: The idea is to store the adjacency list into the dictionaries, which helps to store the graph in any format not only in the form of the integers. Here we have used characters as a reference on those places any custom objects can also be used. Below is the implementation of the above approach: Python3 # Python3 implementation to build a # graph using Dictionaries from collections import defaultdict # Function to build the graph def build_graph(): edges = [ ["A", "B"], ["A", "E"], ["A", "C"], ["B", "D"], ["B", "E"], ["C", "F"], ["C", "G"], ["D", "E"] ] graph = defaultdict(list) # Loop to iterate over every # edge of the graph for edge in edges: a, b = edge[0], edge[1] # Creating the graph # as adjacency list graph[a].append(b) graph[b].append(a) return graph if __name__ == "__main__": graph = build_graph() print(graph) Output: { 'G': ['C'], 'F': ['C'], 'E': ['A', 'B', 'D'], 'A': ['B', 'E', 'C'], 'B': ['A', 'D', 'E'], 'D': ['B', 'E'], 'C': ['A', 'F', 'G'] } Shortest Path between two nodes of graph Approach: The idea is to use queue and visit every adjacent node of the starting nodes that traverses the graph in Breadth-First Search manner to find the shortest path between two nodes of the graph. Below is the implementation of the above approach: Python3 # Python implementation to find the # shortest path in the graph using # dictionaries # Function to find the shortest # path between two nodes of a graph def BFS_SP(graph, start, goal): explored = [] # Queue for traversing the # graph in the BFS queue = [[start]] # If the desired node is # reached if start == goal: print("Same Node") return # Loop to traverse the graph # with the help of the queue while queue: path = queue.pop(0) node = path[-1] # Condition to check if the # current node is not visited if node not in explored: neighbours = graph[node] # Loop to iterate over the # neighbours of the node for neighbour in neighbours: new_path = list(path) new_path.append(neighbour) queue.append(new_path) # Condition to check if the # neighbour node is the goal if neighbour == goal: print("Shortest path = ", *new_path) return explored.append(node) # Condition when the nodes # are not connected print("So sorry, but a connecting"\ "path doesn't exist :(") return # Driver Code if __name__ == "__main__": # Graph using dictionaries graph = {'A': ['B', 'E', 'C'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F', 'G'], 'D': ['B', 'E'], 'E': ['A', 'B', 'D'], 'F': ['C'], 'G': ['C']} # Function Call BFS_SP(graph, 'A', 'D') Output: Shortest path = A B D Comment More infoAdvertise with us Next Article Building an undirected graph and finding shortest path using Dictionaries in Python murtuza_chawala Follow Improve Article Tags : Graph Algorithms Python Data Structures DSA Algorithms-Graph Shortest Paths Quiz python-dict Python dictionary-programs +4 More Practice Tags : AlgorithmsData StructuresGraphpythonpython-dict +1 More Similar Reads Print all shortest paths between given source and destination in an undirected graph Given an undirected and unweighted graph and two nodes as source and destination, the task is to print all the paths of the shortest length between the given source and destination.Examples: Input: source = 0, destination = 5 Output: 0 -> 1 -> 3 -> 50 -> 2 -> 3 -> 50 -> 1 -> 13 min read Difference between the shortest and second shortest path in an Unweighted Bidirectional Graph Given an unweighted bidirectional graph containing N nodes and M edges represented by an array arr[][2]. The task is to find the difference in length of the shortest and second shortest paths from node 1 to N. If the second shortest path does not exist, print 0. Note: The graph is connected, does no 15+ min read Shortest path with one curved edge in an undirected Graph Given an undirected connected graph of n vertices and a list of m edges in a graph and for each pair of vertices that are connected by an edge. There are two edges between them, one curved edge and one straight edge i.e. the tuple (x, y, w1, w2) means that between vertices x and y, there is a straig 12 min read Number of shortest paths in an unweighted and directed graph Given an unweighted directed graph, can be cyclic or acyclic. Print the number of shortest paths from a given vertex to each of the vertices. For example consider the below graph. There is one shortest path vertex 0 to vertex 0 (from each vertex there is a single shortest path to itself), one shorte 11 min read Shortest path with exactly k edges in a directed and weighted graph | Set 2 Given a directed weighted graph and two vertices S and D in it, the task is to find the shortest path from S to D with exactly K edges on the path. If no such path exists, print -1. Examples: Input: N = 3, K = 2, ed = {{{1, 2}, 5}, {{2, 3}, 3}, {{3, 1}, 4}}, S = 1, D = 3 Output: 8 Explanation: The s 8 min read Number of shortest paths in an Undirected Weighted Graph Given a weighted undirected graph G and an integer S, the task is to print the distances of the shortest paths and the count of the number of the shortest paths for each node from a given vertex, S. Examples: Input: S =1, G = Output: Shortest Paths distances are : 0 1 2 4 5 3 2 1 3 Numbers of the sh 15 min read Find if there is a path between two vertices in a directed graph Given a Directed Graph and two vertices src and dest, check whether there is a path from src to dest.Example: Consider the following Graph: adj[][] = [ [], [0, 2], [0, 3], [], [2] ]Input : src = 1, dest = 3Output: YesExplanation: There is a path from 1 to 3, 1 -> 2 -> 3Input : src = 0, dest = 11 min read Generate a graph using Dictionary in Python Prerequisite - Graphs To draw graph using in built libraries - Graph plotting in PythonIn this article, we will see how to implement graph in python using dictionary data structure in python. The keys of the dictionary used are the nodes of our graph and the corresponding values are lists with each 6 min read 0-1 BFS (Shortest Path in a Binary Weight Graph) Given an undirected graph where every edge has a weight as either 0 or 1. The task is to find the shortest path from the source vertex to all other vertices in the graph.Example: Input: Source Vertex = 0 and below graph Having vertices like (u, v, w): edges: [[0,1,0], [0, 7, 1], [1,2,1], [1, 7, 1], 10 min read Dijkstra's shortest path algorithm in Python Given a graph and a source vertex in the graph, find the shortest paths from source to all vertices in the given graph. Dijkstraâs algorithm is a popular algorithm for solving many single-source shortest path problems having non-negative edge weight in the graphs i.e., it is to find the shortest dis 4 min read Like