×

Python Graph

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.

  1. Displaying Vertices of the graph.
  2. Displaying Edges of the graph.
  3. Adding a Vertex.
  4. Adding an Edge.
  5. Creating a Graph.

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:

Python Graph

As we can observe in the above graph

Vertices = {p, q, r, s, t}
Edges = {pq, pr, qs, rs, st}

In Python, the above graph can be represented in the syntax, as shown below:

# Creating a dictionary using the graph elements
 my_graph = {"p" : ["q","r"],
           "q" : ["p", "s"],
           "r" : ["p", "s"],
           "s" : ["t"],
           "t" : ["s"]
          }
 # Printing the final graph       
 print("This is my graph: \n", my_graph) 

The above snippet of code should produce an Output, as shown below:

This is my graph:
 {'p': ['q', 'r'], 'q': ['p', 's'], 'r': ['p', 's'], 's': ['t'], 't': ['s']}

Displaying Vertices of the Graph

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:

class my_graph:
     def __init__(self, g_dict = None):
         if g_dict is None:
             g_dict = []
         self.g_dict = g_dict
 # Geting the keys of the dictionary
     def myVertices(self):
         return list(self.g_dict.keys())
 # Creating a dictionary using the graph elements
 my_graph_elements = {
     "p" : ["q","r"],
     "q" : ["p", "s"],
     "r" : ["p", "s"],
     "s" : ["t"],
     "t" : ["s"]
     }
 x = my_graph(my_graph_elements)
 print("The Vertices of my graph: \n", x.myVertices()) 

The above snippet of code should produce an Output, as shown below:

The Vertices of my graph:
 ['p', 'q', 'r', 's', 't']

Displaying Edges of the Graph

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:

class my_graph:
     def __init__(self, g_dict = None):
         if g_dict is None:
             g_dict = {}
         self.g_dict = g_dict
     def my_edges(self):
         return self.find_my_edges()
 # Finding the distinct list of edges
     def find_my_edges(self):
         edge_name = []
         for vertx in self.g_dict:
             for next_vrtx in self.g_dict[vertx]:
                 if {next_vrtx, vertx} not in edge_name:
                     edge_name.append({vertx, next_vrtx})
         return edge_name
 # Creating a dictionary using the graph elements
 my_graph_elements = {
     "p" : ["q","r"],
     "q" : ["p", "s"],
     "r" : ["p", "s"],
     "s" : ["t"],
     "t" : ["s"]
     }
 x = my_graph(my_graph_elements)
 print("The Edges of my graph: \n", x.my_edges()) 

The above snippet of code should produce an Output, as shown below:

The Edges of my graph:
 [{'q', 'p'}, {'p', 'r'}, {'s', 'q'}, {'s', 'r'}, {'s', 't'}]

Inserting a Vertex

We can add a vertex by adding a key to the graph dictionary. Let’s have a look at an example shown below:

class my_graph:
     def __init__(self, g_dict = None):
         if g_dict is None:
             g_dict = {}
         self.g_dict = g_dict
     def get_Vertices(self):
         return list(self.g_dict.keys())
 # Adding the vertex as a key
     def add_Vertex(self, vertx):
        if vertx not in self.g_dict:
             self.g_dict[vertx] = []
 # Creating a dictionary using the graph elements
 my_graph_elements = {
     "p" : ["q","r"],
     "q" : ["p", "s"],
     "r" : ["p", "s"],
     "s" : ["t"],
     "t" : ["s"]
     }
 x = my_graph(my_graph_elements)
 x.add_Vertex("u")
 print("The Vertices of the graph: \n", x.get_Vertices()) 

The above snippet of code should produce an Output, as shown below:

The Vertices of the graph:
 ['p', 'q', 'r', 's', 't', 'u']

Inserting an Edge

The process of adding an edge to a current graph involves the following procedure:

  • First of all, we need to treat the new vertex as a tuple.
  • Then, we need to validate if any edge is already present.

If no edge is present there, we can add one as shown in the following example:

class my_graph:
     def __init__(self, g_dict = None):
         if g_dict is None:
             g_dict = {}
         self.g_dict = g_dict
     def my_edges(self):
         return self.find_edges()
 # Adding the new edge
     def Add_Edge(self, my_edge):
         my_edge = set(my_edge)
         (vrtx_a, vrtx_b) = tuple(my_edge)
         if vrtx_a in self.g_dict:
             self.g_dict[vrtx_a].append(vrtx_b)
         else:
             self.g_dict[vrtx_a] = [vrtx_b]
 # Listing the edge names
     def find_edges(self):
         edge_name = []
         for vertx in self.g_dict:
             for next_vrtx in self.g_dict[vertx]:
                 if {next_vrtx, vertx} not in edge_name:
                     edge_name.append({vertx, next_vrtx})
         return edge_name
 # Creating a dictionary using the graph elements
 my_graph_elements = {
     "p" : ["q","r"],
     "q" : ["p", "s"],
     "r" : ["p", "s"],
     "s" : ["t"],
     "t" : ["s"]
     }
 x = my_graph(my_graph_elements)
 x.Add_Edge({'p','t'})
 x.Add_Edge({'p','r'})
 print("The Edges of my graph: \n", x.my_edges()) 

The above snippet of code should produce an Output, as shown below:

The Edges of my graph:
 [{'q', 'p'}, {'p', 'r'}, {'q', 's'}, {'s', 'r'}, {'t', 's'}, {'t', 'p'}]

Related Topics

Class and Static Methods in Python

The method is an important concept to learn for every programmer or data analyst. We know that in OOP's concept, each object has its attributes and behaviors defined through methods....

3 minutes read.

Python bin() function

Python bin() function The bin() function in Python returns the binary version for the specified integer. Syntax bin(x) Parameter n: This parameter represents an integer or int value. Return This function returns a binary string for the specified integer...

1 minute read.

Python List

The list is one of the most versatile, mutable data-structures in Python. It can store heterogeneous data or different types of data. The list contains comma-separated values (item) within the square brackets. Creating...

4 minutes read.

Python Set add() Method

Python Set add() Method The set.add() method adds the specified element to a set. If the element is already present in the set, it doesn't add it. Syntax set.add(element) Parameter element- This parameter represents the element that...

1 minute read.

Anaconda python 3 installation for windows 10

If you are a problem solver and like to solve programming questions, the anaconda distribution for python could be one of the best options to use and solve problems in...

3 minutes read.

Python MySQL Database Connection

In this article, you will be able to understand how to connect to a MySQL database through Python. We generally can use many methods or modules to connect to the database...

6 minutes read.

Convert List to Array in Python

What is List in Python? In Python, a list is a built-in data structure that stores a collection of items. The items in a list can be of any data type,...

3 minutes read.

Python String lstrip() method

Python String lstrip() method The string. lstrip () method in Python returns a copy of the string with leading characters removed (based on the string argument passed). Syntax string.lstrip([chars]) Parameter chars(optional): This parameter represents a...

1 minute read.

Python Program to Convert Decimal into Binary, Octal, and Hexadecimal

Python Program to Convert Decimal into Binary, Octal, and Hexadecimal We know that the most widely used number system is a decimal system, but the computer only understands binary values. The...

2 minutes read.

__init__ in python

Every programmer will enclose to object-oriented programming (OOP) these days. As we know, that python is the latest and most modern programming language; python supports to implementation of object-oriented philosophy....

5 minutes read.

Create the First GUI Application using PyQt5 in Python

GUI: A graphical user interface, or GUI, is present on most personal computers. It provides a simple experience for individuals with various computing skill levels. GUI apps may take more resources...

3 minutes read.

PyDev with Python IDE

What is IDE? Integrated Development Environment is the abbreviation of IDE. It is a coding tool that automates code editing, finding errors and testing. IDE combines all the developer tools into...

3 minutes read.

Assertion error in python

In this article, we will discuss assertions in the python programming language. Assertion: Assertions are a way of telling a program to test a certain condition and trigger an error if the...

3 minutes read.

Python String

Python String Python string is considered as the most popular data type present in Python language. In Python, string data type is the collection of characters, letters, white spaces etc. written...

31 minutes read.

Python Banner

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Keyboard Jump Game in Python

Keyword hop (jump) game is a speed composing game that aides in further developing the composing velocity of players The object of Keyboard Jump (hop) Game Python Project is to fabricate...

7 minutes read.

How to Read html page in python

Html is a Hyper Text Markup language is a standard language used for creating webpages. HTML is the name of the language used to describe the construction of Web pages....

4 minutes read.

GUI Calculator in Python

Introduction In Python, we can develop a GUI(Graphical User Interface) with multiple options. It offers us some great and commonly used methods for the development of the Graphical User Interface. Tkinter...

4 minutes read.

Difference between Module and Package in Python

The main difference between the module and the package in Python is that the module can be a simple file in Python that contains the different functions and collection of...

4 minutes read.

Python Network Programming

In network programming, python plays a very important role. Python provides full support for encoding and decoding data and network protocol in its standard library. Writing a network program in...

3 minutes read.