Python program that accepts a sentence and builds a dictionary

 

Python program that accepts a sentence and builds a dictionary

Problem Definition:

Develop a python program that accepts a sentence and builds a dictionary with LETTER, DIGITS, LOWERCASE, and UPPERCASE as key values and their count in the sentence as the values. Example: Str = VTU@123.e-Learning Output: d = {“LETTER”: 12, “DIGITS”: 3, “LOWERCASE”: 8, “UPPERCASE”: 4}

Video tutorial of the program

Solution (Steps)

Step by Step solution to Python program that accepts a sentence and builds a dictionary.

First, read a string variable with the sentence or accept a sentence from the user using the input statement of python.

Initialize, variable, cletter, clowercase, cuppercase, and cdigits to zero. these variables are used to hold the occurrence of each of them in the given sentence.

Read one character from the sentence at a time using for loop. Use if conditional statement to check whether the read character is a digit, letter, uppercase letter, or lowercase letter. Use isdigit() function to check whether the character is a digit. Similarly use isalpha() function to check whether the character is letter, islower() function to check whether the character is a lowercase letter and isupper() function for uppercase letter. Increment the associated variables by one each time depending on the outcome of the if statement.

Finally, create a dictionary with LETTER, DIGITS, LOWERCASE, and UPPERCASE as key and their occurrence in the sentence as values. Then display the dictionary which contains the result using the print statement.

Source code for Python program that accepts a sentence and builds a dictionary

Str = 'VTU@123.e-Learning'
cletter = 0
cdigit = 0
clower = 0
cupper = 0
d = {}
for c in Str:
    if c.isalpha():
        cletter = cletter + 1
    if c.isdigit():
        cdigit = cdigit + 1
    if c.islower():
        clower = clower + 1
    if c.isupper():
        cupper = cupper + 1
        
d['Letter'] = cletter
d['Lower'] = clower
d['Upper'] = cupper
d['Digit'] = cdigit 
print (d)

Output

{'Letter': 12, 'Lower': 8, 'Upper': 4, 'Digit': 3}

Summary:

This tutorial discusses how to build a python program that accepts a sentence and build a dictionary with LETTER, DIGITS, LOWERCASE, and UPPERCASE as key values and their occurrence in the sentence as the values. Do share the tutorial with your friends and have any issues do comment in the comment box.

Leave a Comment

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