How to Generate a graph using Dictionary in Python

In this tutorial, we will Generate a graph using a Dictionary in Python. Dictionary is a collection of data in the form of key-value pair. We use a dictionary to implement a graph because it is easy to store a vertice along with its adjacent vertice as its value. Thus forming an edge.

Generate a graph using Dictionary in Python

Before we start, let us understand some basic terminologies related to graphs. The graph comprises vertices called nodes. Two adjacent vertices make an edge. Graphs in computer science are used in data computation, communication networks, etc.

How to Generate a graph using Dictionary in Python

Python provides a module named collections. This module contains files for generating a graph using a dictionary. Here, we import the function named defaultdict. This function returns the default value of the defined dictionary.

In the above code, the function InsertNewEdge() appends a new edge the user enters to dictionary named as graph[].

Then we append every vertice with its adjacent vertice in the dictionary. Thus forming an edge.

In dictionary, each key acts as vertice which contains all connected vertices as its values.

You can also refer:

Input:

>>>Enter number of vertices to generate: 5
>>>Enter 1  x
>>>Enter 2  y
>>>Enter 1  y
>>>Enter 2  z
>>>Enter 1  p
>>>Enter 2  q
>>>Enter 1  r
>>>Enter 2  s
>>>Enter 1  s
>>>Enter 2  t

Output:

[('x', 'y'), ('y', 'z'), ('p', 'q'), ('r', 's'), ('s', 't')]

Also read: Python dictionary setdefault() method

Leave a Reply

Your email address will not be published. Required fields are marked *