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}

Was this helpful?

India's 1st AI Doubt Solver for CBSE, JEE, and NEET

Ask a Question for Free

and then it's just ₹212 a month

Learn how Chatterbot AI can help you succeed

Cover Image of the article Computer Science Class 11 CBSE - The Ultimate Guide with Notes, Solutions and AI

Computer Science Class 11 CBSE - The Ultimate Guide with Notes, Solutions and AI

This ultimate guide for CBSE Computer Science class 11 has detailed notes, NCERT solutions, cheat sheets, and our free AI-powered doubt-solving assistant, Chatterbot AI.

Cover Image of the article JEE Advanced 2024 Exam Date Announced: Complete Guide to Eligibility, Syllabus, and Preparation Tips

JEE Advanced 2024 Exam Date Announced: Complete Guide to Eligibility, Syllabus, and Preparation Tips

JEE Advanced 2024 on May 26! Get exam schedule, syllabus, prep tips & more in this guide. Ace India's top engineering test with topper strategies.

Cover Image of the article How to Crack NEET: The Ultimate Blueprint to Outsmart the Exam and Unlock Your Medical Dreams

How to Crack NEET: The Ultimate Blueprint to Outsmart the Exam and Unlock Your Medical Dreams

Ace NEET with expert strategies: Discover effective exam strategies, time management, core concepts mastery, problem-solving techniques, revision tips, and AI-assisted doubt clearing with Chatterbot AI.

Cover Image of the article How to Crack IIT: Smart Self-Study Strategies and AI Tools for Success

How to Crack IIT: Smart Self-Study Strategies and AI Tools for Success

Ace IIT JEE in 6 months without coaching. Discover expert self-study strategies for Physics, Chemistry, and Math. Master time management, mock tests, and leverage AI tools like Chatterbot AI for personalized doubt-solving.