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}
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}
✨ Free AI Tools for You
Powered by Chatterbot AI
Answer
Here is a Python program to create a dictionary from a string and track the count of each letter:
def count_letters(string):
# Create an empty dictionary to store the letter counts
letter_counts = {}
# Loop through each character in the string
for char in string:
if char in letter_counts:
# If character is already in the dictionary, increment its count
letter_counts[char] += 1
else:
# If character is not in the dictionary, add it with a count of 1
letter_counts[char] = 1
return letter_counts
# Sample string
sample_string = 'w3resource'
# Call the function and store the result in a variable
result = count_letters(sample_string)
# Print the result
print(result)
Expected output:
{'w': 1, '3': 1, 'r': 2, 'e': 2, 's': 1, 'o': 1, 'u': 1, 'c': 1}
India's 1st AI Doubt Solver for CBSE, JEE, and NEET
Ask a Question for Freeand then it's just ₹212 a month