Python Graph: In Computer Science and Mathematics, a Graph is a pictorial representation of a group of objects or elements where some elements are connected using the links. A graph is the network of vertices (also known as nodes) that may or may not be interconnected. These vertices are connected using a path or a line known as an edge. We will be discussing a lot related to the terms used in the Graph and its various functionalities in this section. We will be discovering various things, such as creating a graph and adding several data elements to the Graph using Python programming.

Let’s start with a basic difference between directed and undirected graphs. If the edges in Graph have a specific flow direction, where the direction edge is known as an arc called Graph is directed. At the same time, the Graph with no specified directions is said to be undirected.
Graph plays a significant role in Data Science and it is often practiced in solving real-world problems. Various sectors depend on the Graph and its theories and principles, including molecular studies in chemistry and biology, maps, networks, recommender systems, and a lot.
These are some basic operations we are going to perform on graphs in the following sections.
We can implement a Graph with the help of Python Dictionary data structures. We will represent the graph vertices as the dictionary keys and the edges as the values associated with each key in the dictionary.
Let’s have a look at the graph shown below:
As we can observe in the above graph
In Python, the above graph can be represented in the syntax, as shown below:
The above snippet of code should produce an Output, as shown below:
We can display the vertices of the graph by finding the keys of the graph dictionary using the keys() method. Let’s have a look at the following example:
The above snippet of code should produce an Output, as shown below:
It is slightly hard to find the edges of a graph than to find the vertices because we need to find each of the vertices pairs that hold an edge in between them. Thus, we can build an empty list holding the edges and then we can iterate through the edge values linked with each of the vertices. Then, we will get the complete list holding the different group of edges originated from the vertices. Let’s have a look at an example given below:
The above snippet of code should produce an Output, as shown below:
We can add a vertex by adding a key to the graph dictionary. Let’s have a look at an example shown below:
The above snippet of code should produce an Output, as shown below:
The process of adding an edge to a current graph involves the following procedure:
If no edge is present there, we can add one as shown in the following example:
The above snippet of code should produce an Output, as shown below:
Designed by Elegant Themes | Powered by WordPress

source