Calculate String Letter Frequencies

  • Share this:

Code introduction


Calculate the frequency of each letter in a string and return a dictionary where the key is the letter and the value is the number of times the letter appears in the string.


Technology Stack : collections.Counter, string.ascii_lowercase

Code Type : String processing

Code Difficulty : Intermediate


                
                    
def a_to_z_frequency(text):
    from collections import Counter
    from string import ascii_lowercase

    def get_frequency(char):
        return Counter(text).get(char, 0)

    frequencies = {char: get_frequency(char) for char in ascii_lowercase}
    return frequencies