Write A Python Program To Create A Dictionary From String

Hi Guys, welcome to my blog in this article you will learn about how to Write A Python Program To Create A Dictionary From String

 

Title : 

Write A Python Program To Create A Dictionary From String


Write A Python Program To Create A Dictionary From String



 

Description : 

Hi guys in this article you will learn about a python program accepts a string from the user and finds the count of letter present in that string and prints it We will be using the dictionary to store the count of letters present in the string and finally use dictionary functions to print all the letters with their count present in the string. Let's take a string variable and use input() function call to accept user input(), also take an empty dictionary to store key as letter and value as count of letters in string..


    

string = input("Enter a String : ")
letter_counter = dict()


    


Use the for loop to iterate all the letters present in the string, using the E statement check if the letter is present in the dictionary then increment the value, else if the letter is first time occurring then initialize to one. Now use another for loop to print all the key and value pairs that are stored in the above dictionary, use the print function.


    

for letter in string:
   if letter in letter_counter:
       letter_counter[letter] += 1
   else:
       letter_counter[letter] = 1

for key, value in letter_counter.items():
   print(f"key {key} occurs : {value} times")


    




Complete Python Code : 


    

string = input("Enter a String : ")
letter_counter = dict()

for letter in string:
   if letter in letter_counter:
       letter_counter[letter] += 1
   else:
       letter_counter[letter] = 1

for key, value in letter_counter.items():
   print(f"key {key} occurs : {value} times")


    

 

 

Output : 


    
Enter a String : code with tj
key c occurs : 1 times
key o occurs : 1 times
key d occurs : 1 times
key e occurs : 1 times
key   occurs : 2 times
key w occurs : 1 times
key i occurs : 1 times
key t occurs : 2 times
key h occurs : 1 times
key j occurs : 1 times


    

 

Output : 


    
Enter a String : this is a program
key t occurs : 1 times
key h occurs : 1 times
key i occurs : 2 times
key s occurs : 2 times
key   occurs : 3 times
key a occurs : 2 times
key p occurs : 1 times
key r occurs : 2 times
key o occurs : 1 times
key g occurs : 1 times
key m occurs : 1 times


    



Conclusion :

The above Python program takes a string as user input and then take an Empty dictionary to calculate the count of letters present in the string It uses the for loop to iterate all the letters present in the string and create a dictionary out of it, then prints the dictionary Comment it down below if you have any query is regarding the above Python program

 

Post a Comment

0 Comments