Saturday, 23 May 2020

Python program to build Dictionary using sentence

What is a Dictionary in Python Programming?

Dictionary is a special data type in a python. It stored record in the form of (Key, Value). Each entry in the dictionary is accessed by 'Key' only. You cannot use index (like List, Tuple) for accessing the elements.

How to create Dictionary?

dictionary_name=dict()

Ex. d=dict()

or

dictionary_name={key1:value1, key2:value2,.....}

Ex. d={1:'Apple', 2:'Ball', 3:'Cat'}

Program 1:

In this program, one string (sentence) is given as input. 
Once, input is received, it is splitted on the basis of blank space, which results into a list.
Therefore, 'str' contains list of words and not string/sentence.
After that we will traverse through the list and simply add each word into a dictionary in (Key, Value) pair.

#Program: To create Dictionary using String Senetence
#Author: Hitendra E. Suryavanshi

str=input("Enter a sentence").split()
d=dict()
for word in str:
    d[word[0]]=word
print(d)

So, the output of the program is dictionary 'd', given as below.

Output 1:

Enter a sentence:Welcome To India
{'W': 'Welcome', 'T': 'To', 'I': 'India'}

The problem with this program is that, if you have two or more words starting with same character, it will keep only last entry into the dictionary. Because it updates the entry for that character.

Look at the example  below.
Here two words 'Python' and 'Programming' starts with same character 'P'.
Therefore, it will keep only last entry i.e. 'Programming' for character 'P'.

Output 2:

Enter a sentence:Python is Programming Language
{'P': 'Programming', 'i': 'is', 'L': 'Language'}


Program 2:

The problem in program 1 is solved into program 2, given below.
Here, in order to solve the problem, we first check for the 'Key', wether that 'Key' exists in a Dictionary or not?.
If not, then we will add new record (key, value) to the dictionary.
If yes, then we will read previous entries and append new 'value' to it, and update the dictionary.

Go through the below program for the answer.

#Program: To create Dictionary using String Senetence
#Author: Hitendra E. Suryavanshi

str1=input("Enter a sentence:").split()
d=dict()
for word in str1:
    key=word[0]
    value=word
    if key in d:
        d[key]=d[key]+[value]
    else:
        d[key]=[value]
print(d)


Enter a sentence:Python is Programming Language
{'P': ['Python', 'Programming'], 'i': ['is'], 'L': ['Language']}


Thank You
Hitendra E. Suryavanshi
M.Tech.(IT), BE (IT)

No comments:

Post a Comment

How to take input in Python?

How to read input in Python? In Python 3, input() function is used for taking input from the keyboard. The input() function in Python 3 i...