Question 03 of 04

Sentence Letter Frequency Counter using Dictionary

Write a Python function that takes a sentence as input from the user and calculates the frequency of each letter. Use a variable of dictionary type to maintain the count.

C++
def calculate_letter_frequency(sentence):
    """
    Calculates the frequency of each letter in a sentence using a dictionary.
    Ignores non-alphabetic characters and treats case-insensitively.
    """
    frequency_dict = {}
    
    for char in sentence:
        if char.isalpha():
            letter = char.lower()
            frequency_dict[letter] = frequency_dict.get(letter, 0) + 1
            
    return frequency_dict

def main():
    user_sentence = input("Enter a sentence: ")
    
    freq = calculate_letter_frequency(user_sentence)
    
    print("\n--- LETTER FREQUENCY DISTRIBUTION ---")
    print(f"{'Letter':<10}{'Count':<10}")
    print("-" * 20)
    for letter, count in sorted(freq.items()):
        print(f"{letter:<10}{count:<10}")

if __name__ == "__main__":
    main()
Question 3 of 4