×

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

Python Modules List

Python is like an ocean. If you have been working with Python, you might’ve already heard the word module. When we solve a problem in mathematics, there will be several...

3 minutes read.

App Config Python

An XML file called App. Config serves as the document for any programme. In other terms, you can modify any configuration inside of it without going to edit the code...

7 minutes read.

Python Abstract Class

An Introduction to Abstract Classes An Abstract Class is one of the most significant concepts of Object-Oriented Programming (OOP). An Abstract class can be deliberated as a blueprint or design for...

6 minutes read.

How to Parse JSON in Python

JSON The JSON, the Java Script Object Notation, is an open standard file designed for data interchange; it is light-weighted text. The JSON uses human-readable text to store and transmit the...

4 minutes read.

Python Kwargs Example

In this article, we'll talk about Python's kwargs notion. In Python, kwargs has two stars and passes a variable number of keyworded argument lists to the function, whereas args has...

5 minutes read.

Python Variables, Constants and Literals

Python is today's most valuable, easy-to-implement and sought-out programming language. Nowadays, developers want to focus on implementing the program rather than spending time with complex programs. So, for this reason,...

17 minutes read.

How to declare array in python

How to declare array in python? Arrays are a great way of storing our numeric values into a variable in continuous locations. For declaring an array in C language, we used...

4 minutes read.

wxPython Panel class

wxPython Panel class The Widgets which is shown in the frame of GUI window such as text box, buttons, static text etc. are put inside the panel class of the wxpython...

2 minutes read.

Iterate through the list in Python

One of the six basic data types of the Python computer language is the list. You must be familiar with the methods and functions that deal with lists in order...

7 minutes read.

How to find square root in python

How to find Square Root of a number In Python Python makes a lot of tasks easier by using different functions, modules, and libraires. There is an inbuilt function in Python...

6 minutes read.

Number Pattern Programs in Python

Learning Python is very easy, and it understands in better way compared to other programming languages. One of the many reasons why it has emerged as the most widely used...

4 minutes read.

Character Set in Python

A collection of legal characters that will recognize by a programming language known as a Character set. Taking python programming language as an instance. The set of characters supported by the...

6 minutes read.

How to create a login page in python

Users can access an application by providing their username and Password or by authenticating with a social media login on the login screen. Python Tkinter Python provides a variety of choices for...

3 minutes read.

Python String upper() method

Python String upper() method The string.upper() method in Python returns a copy of the string converted to uppercase. Syntax string.upper() Parameter NA Return This method returns a copy of the string converted to uppercase. Example 1 # Python...

1 minute read.

Palindrome In Python

What is Palindrome? A Palindrome can be defined as the number or a string that resides unchanged when it is reversed. Example: 14341 Output: Yes, this is a Palindrome number Example: RACECAR Output: Yes, this...

2 minutes read.

Python Algorithms

A quote goes, "A goal without a plan is just a wish." To achieve anything in life, we can't simply go for it without making a plan and sticking to...

4 minutes read.

Python String ljust() method

Python String ljust() method The string.ljust() method in Python will left align the string, where the padding is done using the parameter fillchar (space is default). Syntax String.ljust(width[, fillchar]) Parameter width: This parameter represents the...

2 minutes read.

Difference Between Python and Scala

What is Python? Python is a high-level general-purpose interpreted programing language. It is used for multi general-purpose work such as language construct as well as its object-oriented approach aims to help...

4 minutes read.

Difference between Input() and raw_input() functions in Python

There are two input functions in Python that are used for taking input are given below: raw_input()input() What is raw_input() Function? raw_input() function is a built-in function in Python. It is used to...

6 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.