Python program to calculate character frequency in a string

Learn to calculate the frequency of every character in Python 3.

Python program to calculate character frequency in a string

Method 1 - Simple for loop

Code

user_input = input("Provide a string ==> ")
counter_dict = dict()

for char in user_input:
    if char in counter_dict.keys():
        counter_dict[char] += 1
    else:
        counter_dict[char] = 1

print(counter_dict)

Output

Provide a string ==> Pylenin
{'P': 1, 'y': 1, 'l': 1, 'e': 1, 'n': 2, 'i': 1}

Method 2 - Using count() method and set

Code

user_input = input("Provide a string ==> ")
counter_dict = dict()

char_set = set(user_input)

for char in char_set:
    counter_dict[char] = user_input.count(char)
print(counter_dict)

Output

Provide a string ==> Pylenin
{'l': 1, 'P': 1, 'y': 1, 'e': 1, 'i': 1, 'n': 2}

Method 3 - Using collections library

Code

from collections import Counter

user_input = input("Provide a string ==> ")
counter_dict = Counter(user_input)
print(counter_dict)

Output

Provide a string ==> Pylenin
Counter({'n': 2, 'P': 1, 'y': 1, 'l': 1, 'e': 1, 'i': 1})

Method 4 - Using dict.get() method

Code

user_input = input("Provide a string ==> ")
counter_dict = dict()

for char in user_input:
    counter_dict[char] = counter_dict.get(char, 0) + 1
print(counter_dict)

Output

Provide a string ==> pylenin
{'p': 1, 'y': 1, 'l': 1, 'e': 1, 'n': 2, 'i': 1}

Subscribe to Pylenin

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe