Python Practice › Dictionary Programs › Program 10
Character counts of a string
Write a Python program to build a dictionary of character counts from a string.
Input
"SQATools"
Output
{'S': 1, 'Q': 1, 'A': 1, 'T': 1, 'o': 2, 'l': 1, 's': 1}Approach
get(ch, 0) + 1for each character.
Solution
text = "SQATools"counts = {}for ch in text: counts[ch] = counts.get(ch, 0) + 1print(counts)Output
{'S': 1, 'Q': 1, 'A': 1, 'T': 1, 'o': 2, 'l': 1, 's': 1}Learn the concept
New to this topic? Read the lesson, then come back.