Counter Most Common in Python

Level 4187 keystrokes

This uses Counter to count element frequencies and most_common() to find the most frequent elements.

Python code

# Import Counter from collections
1from collections import Counter
2
# The string to analyze
3text = "abracadabra"
# Counter counts how often each character appears
4counter = Counter(text)
5
# Show all counts as a dict, in first-seen order
6print(f"All: {dict(counter)}")
# Top 3 by count; b and r tie at 2 and keep first-seen order
7print(f"Top 3: {counter.most_common(3)}")
# Look up one character like a dict key: 'a' appears 5 times
8print(f"'a' count: {counter['a']}")

Output

All: {'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1}
Top 3: [('a', 5), ('b', 2), ('r', 2)]
'a' count: 5
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • "× 8
  • (× 6
  • )× 6
  • '× 4
  • :× 3
  • {× 3
  • }× 3
  • =× 2
  • _× 1
  • .× 1

More Python examples at level 4

← Python typing practice