English

Write a Python program to create a dictionary from a string. Note: Track the count of the letters from the string. Sample string: 'w3resource' Expected output : {'3': 1, 's': 1, 'r': 2 - Computer Science (Python)

Advertisements
Advertisements

Question

Write a Python program to create a dictionary from a string.

Note: Track the count of the letters from the string.

Sample string: 'w3resource'
Expected output : {'3': 1, 's': 1, 'r': 2, 'u': 1, 'w': 1, 'c': 1, 'e': 2, 'o': 1}
Answer in Brief

Solution

Program:
#Count the number of times a character appears in a given string
st = input("Enter a string: ")

dic = {}
#creates an empty dictionary

for ch in st:
    if ch in dic:
#if next character is already in the dictionary
        dic[ch] += 1
    else:
#if ch appears for the first time
        dic[ch] = 1

#Printing the count of characters in the string
print(dic)

OUTPUT:
Enter a string: meritnation
{'m': 1, 'e': 1, 'r': 1, 'i': 2, 't': 2, 'n': 2, 'a': 1, 'o': 1}
shaalaa.com
Introduction to Dictionaries
  Is there an error in this question or solution?
Chapter 10: Tuples and Dictionaries - Exercise [Page 225]

APPEARS IN

NCERT Computer Science [English] Class 11
Chapter 10 Tuples and Dictionaries
Exercise | Q 4. | Page 225
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×