Python Program to Count the Numbers of Characters in the String and Store Them in a Dictionary Data Structure

Aim:

Write a program to count the numbers of characters in the string and store them in a
dictionary data structure

Program:

str=input("Enter a String:")
dict = {}
for n in str:
keys = dict.keys()
if n in keys:
dict[n] += 1
else:
dict[n] = 1
print (dict) 

(or)

str=input("Enter a String")
dict = {}
for i in str: 
dict[i] = str.count(i)
print (dict) 

Output:

Enter a String: guntur
{'g': 1, 'u': 2, 'n': 1, 't': 1, 'r': 1} 

(or)

str=input("Enter a String")
dist={}
L=len(str);
d={str:L};
print(d)

Output:

Enter a Stringguntur
{'guntur': 6} 

Leave a Comment