Generate a graph using Dictionary in Python
Last Updated :
13 Sep, 2023
Prerequisite – Graphs
To draw graph using in built libraries – Graph plotting in Python
In 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 nodes, which are connecting by an edge.
This simple graph has six nodes (a-f) and five arcs:
a -> c
b -> c
b -> e
c -> a
c -> b
c -> d
c -> e
d -> c
e -> c
e -> b
It can be represented by the following Python data structure. This is a dictionary whose keys are the nodes of the graph. For each key, the corresponding value is a list containing the nodes that are connected by a direct arc from this node.
graph = { "a" : ["c"],
"b" : ["c", "e"],
"c" : ["a", "b", "d", "e"],
"d" : ["c"],
"e" : ["c", "b"],
"f" : []
}
Graphical representation of above example:

defaultdict: Usually, a Python dictionary throws a KeyError if you try to get an item with a key that is not currently in the dictionary. defaultdict allows that if a key is not found in the dictionary, then instead of a KeyError being thrown, a new entry is created. The type of this new entry is given by the argument of defaultdict.
Python Function to generate graph:
# definition of function
def generate_edges(graph):
edges = []
# for each node in graph
for node in graph:
# for each neighbour node of a single node
for neighbour in graph[node]:
# if edge exists then append
edges.append((node, neighbour))
return edges
Implementation:
Python3
from collections import defaultdict
graph = defaultdict( list )
def addEdge(graph,u,v):
graph[u].append(v)
def generate_edges(graph):
edges = []
for node in graph:
for neighbour in graph[node]:
edges.append((node, neighbour))
return edges
addEdge(graph, 'a' , 'c' )
addEdge(graph, 'b' , 'c' )
addEdge(graph, 'b' , 'e' )
addEdge(graph, 'c' , 'd' )
addEdge(graph, 'c' , 'e' )
addEdge(graph, 'c' , 'a' )
addEdge(graph, 'c' , 'b' )
addEdge(graph, 'e' , 'b' )
addEdge(graph, 'd' , 'c' )
addEdge(graph, 'e' , 'c' )
print (generate_edges(graph))
|
Output
[('a', 'c'), ('b', 'c'), ('b', 'e'), ('c', 'd'),
('c', 'e'), ('c', 'a'), ('c', 'b'), ('e', 'b'),
('e', 'c'), ('d', 'c')]
As we have taken example of undirected graph, so we have print same edge twice say as (‘a’,’c’) and (‘c’,’a’). We can overcome this with use of directed graph.
Below are some more programs on graphs in python:
To generate the path from one node to the other node:
Using Python dictionary, we can find the path from one node to the other in a Graph. The idea is similar to DFS in graphs.
In the function, initially, the path is an empty list. In the starting, if the start node matches with the end node, the function will return the path. Otherwise the code goes forward and hits all the values of the starting node and searches for the path using recursion.
Python3
graph = {
'a' : [ 'c' ],
'b' : [ 'd' ],
'c' : [ 'e' ],
'd' : [ 'a' , 'd' ],
'e' : [ 'b' , 'c' ]
}
def find_path(graph, start, end, path = []):
path = path + [start]
if start = = end:
return path
for node in graph[start]:
if node not in path:
newpath = find_path(graph, node, end, path)
if newpath:
return newpath
print (find_path(graph, 'd' , 'c' ))
|
Program to generate all the possible paths from one node to the other.:
In the above discussed program, we generated the first possible path. Now, let us generate all the possible paths from the start node to the end node. The basic functioning works same as the functioning of the above code. The place where the difference comes is instead of instantly returning the first path, it saves that path in a list named as ‘paths’ in the example given below. Finally, after iterating over all the possible ways, it returns the list of paths. If there is no path from the starting node to the ending node, it returns None.
Implementation:
Python3
graph = {
'a' :[ 'c' ],
'b' :[ 'd' ],
'c' :[ 'e' ],
'd' :[ 'a' , 'd' ],
'e' :[ 'b' , 'c' ]
}
def find_all_paths(graph, start, end, path = []):
path = path + [start]
if start = = end:
return [path]
paths = []
for node in graph[start]:
if node not in path:
newpaths = find_all_paths(graph, node, end, path)
for newpath in newpaths:
paths.append(newpath)
return paths
print (find_all_paths(graph, 'd' , 'c' ))
|
Output
[['d', 'a', 'c'], ['d', 'a', 'c']]
Program to generate the shortest path.:
To get to the shortest from all the paths, we use a little different approach as shown below. In this, as we get the path from the start node to the end node, we compare the length of the path with a variable named as shortest which is initialized with the None value. If the length of generated path is less than the length of shortest, if shortest is not None, the newly generated path is set as the value of shortest. Again, if there is no path, it returns None
Implementation:
Python3
graph = {
'a' :[ 'c' ],
'b' :[ 'd' ],
'c' :[ 'e' ],
'd' :[ 'a' , 'd' ],
'e' :[ 'b' , 'c' ]
}
def find_shortest_path(graph, start, end, path = []):
path = path + [start]
if start = = end:
return path
shortest = None
for node in graph[start]:
if node not in path:
newpath = find_shortest_path(graph, node, end, path)
if newpath:
if not shortest or len (newpath) < len (shortest):
shortest = newpath
return shortest
print (find_shortest_path(graph, 'd' , 'c' ))
|
Similar Reads
Iterate over a dictionary in Python
In this article, we will cover How to Iterate Through a Dictionary in Python. To Loop through values in a dictionary you can use built-in methods like values(), items() or even directly iterate over the dictionary to access values with keys. How to Loop Through a Dictionary in PythonThere are multip
6 min read
Sparse Matrix in Python using Dictionary
A sparse matrix is a matrix in which most of the elements have zero value and thus efficient ways of storing such matrices are required. Sparse matrices are generally utilized in applied machine learning such as in data containing data-encodings that map categories to count and also in entire subfie
2 min read
Create a Cycle Graph using Networkx in Python
A cycle graph is a graph which contains a single cycle in which all nodes are structurally equivalent therefore starting and ending nodes cannot be identified. Properties:Number of nodes in a Cycle Graph(Cn) are equal to N.Number of edges in a Cycle Graph(Cn) are equal to N.Every node is connected t
2 min read
Python - Frequencies of Values in a Dictionary
Sometimes, while working with python dictionaries, we can have a problem in which we need to extract the frequency of values in the dictionary. This is quite a common problem and has applications in many domains including web development and day-day programming. Let's discuss certain ways in which t
4 min read
Complete Graph using Networkx in Python
A complete graph also called a Full Graph it is a graph that has n vertices where the degree of each vertex is n-1. In other words, each vertex is connected with every other vertex. Example: Complete Graph with 6 edges: Properties of Complete Graph: The degree of each vertex is n-1.The total number
3 min read
Python Nested Dictionary
A Dictionary in Python works similarly to the Dictionary in the real world. The keys of a Dictionary must be unique and of immutable data types such as Strings, Integers, and tuples, but the key values can be repeated and be of any type. What is Python in Nested Dictionary? Nesting Dictionary means
3 min read
Python | Set 4 (Dictionary, Keywords in Python)
In the previous two articles (Set 2 and Set 3), we discussed the basics of python. In this article, we will learn more about python and feel the power of python. Dictionary in Python In python, the dictionary is similar to hash or maps in other languages. It consists of key-value pairs. The value ca
5 min read
How to Add Duplicate Keys in Dictionary - Python
In Python, dictionaries are used to store key-value pairs. However, dictionaries do not support duplicate keys. In this article, we will explore several techniques to store multiple values for a single dictionary key. Understanding Dictionary Key ConstraintsIn Python, dictionary keys must be unique.
3 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
How To Convert Generator Object To Dictionary In Python
We are given a generator object we need to convert that object to dictionary. For example, a = (1, 2, 3), b = ('a', 'b', 'c') we need to convert this to dictionary so that the output should be {1: 'a', 2: 'b', 3: 'c'}. Using a Generator ExpressionA generator expression can be used to generate key-va
3 min read