Character counts of a string

EasyDictionary Programs · 10 of 94

Write a Python program to build a dictionary of character counts from a string.

Advertisement
Input
"SQATools"
Output
{'S': 1, 'Q': 1, 'A': 1, 'T': 1, 'o': 2, 'l': 1, 's': 1}

Approach

  1. get(ch, 0) + 1 for each character.

Solution

Python
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}
Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More dictionary programs

← All 94 Dictionary Programs