String to A-Z Letter Frequency Counter

  • Share this:

Code introduction


This function takes a string as input and returns a dictionary that contains the count of each letter in the string, only including the letters a to z, and sorted by the letters.


Technology Stack : collections.Counter, string.ascii_lowercase

Code Type : Function

Code Difficulty : Intermediate


                
                    
def a_to_z_counter(input_string):
    from collections import Counter
    from string import ascii_lowercase
    
    # Count the occurrences of each letter in the input string
    letter_counts = Counter(input_string.lower())
    
    # Filter out the letters that are not in the ascii_lowercase
    filtered_counts = {letter: count for letter, count in letter_counts.items() if letter in ascii_lowercase}
    
    # Sort the dictionary by the letters
    sorted_counts = dict(sorted(filtered_counts.items()))
    
    return sorted_counts