Question 12 of 14intermediate🔧 ApplyLong Answer4 marks

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}

Correct Answer

python

Program to create a dictionary from a string

Tracking the count of letters from the string

st = input("Enter a string: ") dic = {} # creates an empty dictionary

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

print(dic)

Output:

Enter a string: w3resource {'w': 1, '3': 1, 'r': 2, 'e': 2, 's': 1, 'o': 1, 'u': 1, 'c': 1}

Explanation:

The program begins by taking a string input from the user and storing it in the variable st. An empty dictionary dic is created using curly braces {} to store the character counts.

A for loop iterates through each character ch in the string. Inside the loop, an if-else condition checks whether the character already exists as a key in the dictionary using the in operator. If the character is present, its corresponding value (count) is incremented by 1. If the character appears for the first time, it is added to the dictionary with an initial count of 1. Finally, the print() function displays the complete dictionary showing each character and its frequency. The dictionary is created with key-value pairs where keys are characters and values are their counts.

Exercise: PROGRAMMING PROBLEMS | Q: 4 | (Page 19)
For More Understanding

Explanation

The answer follows the program structure shown in Program 10-8 from the textbook context. It demonstrates creating an empty dictionary using curly braces, iterating through a string with a for loop, checking membership using the 'in' operator, and updating dictionary values. The program correctly tracks character frequency by incrementing counts for existing keys and initializing new keys with value 1.

Solution Steps

  1. Step 1: Accept string input from user

  2. Step 2: Create an empty dictionary using curly braces

  3. Step 3: Iterate through each character in the string using for loop

  4. Step 4: Check if character exists as key in dictionary using 'in' operator

  5. Step 5: If exists, increment the value by 1; else initialize with value 1

  6. Step 6: Print the final dictionary