Python Practice › Loop Programs › Program 26
Frequency of each digit
Write a Python program to find how often each digit appears in an integer.
Input
1223334441
Output
1 -> 2 2 -> 2 3 -> 3 4 -> 3
Approach
- Use a dictionary of counts, filled one digit at a time.
Solution
n = 1223334441counts = {}while n > 0: d = n % 10 counts[d] = counts.get(d, 0) + 1 n //= 10for digit in sorted(counts): print(digit, "->", counts[digit])Output
1 -> 2 2 -> 2 3 -> 3 4 -> 3
Line by line
Line 5
get(d, 0) returns 0 the first time a digit is seen.
Line 7
Sorting the keys prints the digits in order.
Learn the concept
New to this topic? Read the lesson, then come back.