Building an undirected graph and finding shortest path using Dictionaries in Python Last Updated : 15 Dec, 2021 Summarize Comments Improve Suggest changes Share 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 Dijkstra's shortest path algorithm in Python M murtuza_chawala Follow Improve Article Tags : Python Algorithms-Graph Shortest Paths Quiz python-dict Python dictionary-programs Practice Tags : pythonpython-dict Similar Reads 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 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 Creating a Path Graph Using Networkx in Python A path graph is a connected graph denoted by Pn if it contains n nodes. Nodes are connected in form of a straight line in a path graph. Here we will discuss how networkx module can be used to generate one using its inbuilt path_graph() function. Properties of Path Graph:The number of nodes in a path 2 min read Find Shortest Path Using Python OSMnx Routing Module This article demonstrates how to use the OSMnx routing module to find the shortest path, illustrated with practical examples. Syntax of osmnx.routing.shortest_path() FunctionOSMnx routing module has the 'shortest_path' functionality to find the nearest path from the origin node to the destination no 3 min read Maximize shortest path between given vertices by adding a single edge Given an undirected graph of N nodes and M vertices. You are also given a K edges as selected[]. The task to maximize the shortest path length between node 1 to node N by adding single edges between any two vertices from the given selected edges. Note: You may add an edge between any two selected ve 11 min read Python Program for Detect Cycle in Graph using DSU Prerequisite: Introduction to Disjoint Set Given an undirected graph, The task is to detect if there is a cycle in the given graph. Example: Input:Â N = 4, E = 4Â Output: Yes Explanation: The diagram clearly shows a cycle 0 to 2 to 1 to 0 Input: N = 4, E = 3 Output: No Explanation: There is no cycle 4 min read Like