Alphabetical Letter Count in Text

  • Share this:

Code introduction


This function takes a string as an argument and returns a dictionary. The dictionary contains the count of each letter in the string and is sorted alphabetically by the letter. The keys of the dictionary are letters, and the values are the corresponding counts.


Technology Stack : collections, string

Code Type : Function

Code Difficulty : Intermediate


                
                    
def a_to_z_counter(text):
    from collections import Counter
    import string

    # Count occurrences of each letter in the text
    letter_counts = Counter(text.lower())

    # Filter out non-alphabetic characters and sort by alphabetical order
    result = {char: count for char, count in sorted(letter_counts.items(), key=lambda item: string.ascii_lowercase.index(item[0]))}

    return result