Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

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.

BeginnerPhase 5 - Category 1: Basic String HandlingExample 10 of 10
count-each-character.py
1# Take string input
2s = input("Enter a string: ")
3
4# Count characters
5freq = {}
6for char in s:
7 freq[char] = freq.get(char, 0) + 1
8
9# Display
10for 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. 1

    Increment freq for every source character.

  2. 2

    Sort the character-count pairs.

  3. 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.