Count how many times each character appears in a string using a dictionary
Expt. No.23
Page No.46
Character frequency with a dictionary
Aim
To write a Python program that counts the number of times each character appears in a string, using a dictionary.
Concepts used
Algorithm
- Input a string and create an empty dictionary.
- For each character: if it is already a key, add 1 to its value; otherwise add it with value 1.
- Display each key with its count.
Program
# Character frequency in a string using a dictionary text = input("Enter a string: ")freq = {}for ch in text: if ch in freq: freq[ch] = freq[ch] + 1 else: freq[ch] = 1 print("Character : Count")for ch in freq: print(" ", ch, " :", freq[ch])
A marked line continues the line above it. In your file, write it on the same line.
Output
$ python character_frequency_dictiona.py
Enter a string: programming
Character : Count
p : 1
r : 2
o : 1
g : 2
a : 1
m : 2
i : 1
n : 1
✓ Printed by running this program, not typed by hand.
Result
In "programming", r, g and m appeared twice each and p, o, a, i and n once each. The dictionary kept the characters in the order they first appeared.
Viva voce: what the examiner may ask
01What does ch in freq check for a dictionary?
Whether ch is one of the keys (not the values).
02Why can't you write freq[ch] = freq[ch] + 1 for a new character?
The key does not exist yet, so reading freq[ch] raises KeyError.
03Can a dictionary have two equal keys?
No. Keys are unique; assigning to an existing key replaces its value.
04How can get() shorten the loop?
freq[ch] = freq.get(ch, 0) + 1 gives 0 for a missing key.
Variations for the lab test
- Rewrite the loop with
get(). - Count words in a sentence instead of characters.
- Display only the characters that appear more than once.
! Common mistake Starting a new key at 0 instead of 1 makes every count one too small.