Count Each Character
Count every distinct character with a dictionary. Students update frequencies, include spaces, and display key-count pairs in character-code sorting order.
1# Take string input2s = input("Enter a string: ")34# Count characters5freq = {}6for char in s:7 freq[char] = freq.get(char, 0) + 189# Display10for char, count in sorted(freq.items()):11 print(f"{char}: {count}")
Output
Enter a string: hello e: 1 h: 1 l: 2 o: 1
In this one
- Count dictionary keys
- Keep character case separate
- Sort a frequency display
How it works
- 1
Increment freq for every source character.
- 2
Sort the character-count pairs.
- 3
Print one line for each distinct character.
Edge cases
Are A and a combined?
Are A and a combined?
No. They are different keys.
Are spaces counted?
Are spaces counted?
Yes. Every source character participates.
What's going on
freq uses each character as a key. get(char, 0) supplies a starting zero before the current occurrence adds one.
The sorted items traversal prints one row per distinct character. Uppercase and lowercase letters remain separate, and spaces receive their own counts. Sorting follows string ordering, not a locale-aware alphabet. Empty input creates no rows because there are no dictionary entries.
Are A and a combined? No. They are different keys.
Are spaces counted? Yes. Every source character participates.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why use sorted(freq.items())?
Pick an answer to check it.
Question 2
Are A and a combined?
Pick an answer to check it.
Questions people ask
Are A and a combined?
No. They are different keys.
Are spaces counted?
Yes. Every source character participates.
Why use sorted(freq.items())?
To make the display order predictable.
๐Related Content
- ๐
Phase 5 - Learn Concepts
Review Phase 5 concepts and explanations
- ๐
Phase 5 - Quiz
Test your Phase 5 understanding with quiz questions
- ๐ป
Phase 5 - All Practice Problems
Explore all practice problems for Phase 5
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum