Python Practice › String Programs › Program 28
Frequency of each character
Write a Python program to count how often each character appears in a string.
Input
"sqatools"
Output
{'s': 2, 'q': 1, 'a': 1, 't': 1, 'o': 2, 'l': 1}
TrueApproach
- Build a dictionary of counts, or use
Counter.
Solution
text = "sqatools"freq = {}for ch in text: freq[ch] = freq.get(ch, 0) + 1print(freq) from collections import Counterprint(Counter(text) == freq)Output
{'s': 2, 'q': 1, 'a': 1, 't': 1, 'o': 2, 'l': 1}
TrueLine by line
Line 4
get(ch, 0) handles the first time a character appears.
Learn the concept
New to this topic? Read the lesson, then come back.