×

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 all() Function

Python all() Function The all() function in Python returns a Boolean value ‘True’ if all the items in iterable are true or if the iterable object is empty, else it returns False. Syntax all(iterable) Parameter Iterable: An iterable object...

1 minute read.

Python Dictionary pop() method

Python Dictionary pop() method The dictionary.pop() method in removes the specified item and returns an element from a dictionary having the given key. Syntax dictionary.pop(key[, default]) Parameter key – This argument signifies the key which is to...

2 minutes read.

SKLearn Clustering

These are ml methods thatare responsible for detecting patterns and the similarities within the data.The clustering methods are unsupervised.Here the data is clustered to form groups with the help of...

3 minutes read.

How to Open a file in python with Path

In this tutorial, we will see rather than the traditional way of opening a file by locating or navigating it from our desktops; we will learn how to open the...

2 minutes read.

How to Iterate a List in Python

As we know, a List is one of the four unique data structures available in Python; in this article, we will deep dive into understanding iterating through a list and...

3 minutes read.

Isodate Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

Sklearn in Python

Scikit-learn or sklearn is a machine learning library used in Python that provides many unsupervised and supervised learning tools and algorithms. David Cournapeau first created it as a 2007 Google...

7 minutes read.

Commands in Python

In this tutorial, we will see some of the widely used python commands along with their syntaxes and examples. To make Python more user-friendly, developers have provided these commands to...

12 minutes read.

Python String rstrip() method

Python String rstrip() method The string.rstrip() method in Python returns a copy of the string with trailing characters removed. Syntax string.rstrip([chars]) Parameter chars:  This argument represents a string specifying the set of characters to be...

1 minute read.

Text detection using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Artificial intelligence mini projects with source code in Python

Project Name: Movie recommendation system A recommendation provides customers with relevant information related to their searches. Before the recommendation system, the most common method of purchasing was to rely on the...

4 minutes read.

Decision Tree Classification in Python

In this article, we will learn the implementation of the decision tree in Sklearn, which is nothing but the Scikit Learn library of python. First, we should learn what classification...

12 minutes read.

Python Set symmetric_difference() method

Python Set symmetric_difference() method The set.symmetric_difference() method returns a new set, which is the symmetric difference of two sets. The returned set contains only the unique items and, hence, deleting the common elements of...

2 minutes read.

Comment starts with the symbol in Python

Python programming language: 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...

3 minutes read.

Python String isdigit() method

Python String isdigit() method The string.isdigit() method returns a boolean value true if all characters in the string are digits else for any other value it returns false. Syntax string.isdigit() Parameter NA Return This method returns a...

2 minutes read.

Python Linked List

Linked List Linked lists non-contiguous linear data structure which is made up of nodes and used to store value and a pointer pointing to the next node. It is linked with...

6 minutes read.

Python Errors and exceptions

Exceptions and errors are the obstacles a programmer constantly faces while writing a program. Firstly, we need to understand what are errors and exceptions and the difference between these two...

6 minutes read.

Crash Course on Python by Google

There is a new, free Python programming course offered by Google on Coursera. No programming experience is necessary. There are numerous Python courses available, but when you learn that Google is...

5 minutes read.

Implementing geometric shapes into the game in python

Geometric Drawings We are trying to draw various shapes of geometry by using pygame module to implement Geometric Drawings in game. Let us revise few syntax of basic shapes, to get started...

7 minutes read.

NSE Tools In Python

About NSE NSE (National Stock Exchange) of India Limited is the advanced stock exchange of India. It is located in Mumbai, Maharastra and It was organized in 1992. It was...

2 minutes read.