Counter Usage in Python

Level 5125 keystrokes

This uses Counter to count character occurrences. Counter provides convenient methods like most_common() for frequency analysis.

Python code

# Import Counter from collections module
1from collections import Counter
2
# Define a string to analyze
3text = "abracadabra"
# Counter automatically counts each character's occurrences
# Creates a dict-like object: {'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1}
4counts = Counter(text)
# most_common(n) returns the n most frequent elements as (element, count) tuples
5print(counts.most_common(3))
# Convert Counter to regular dict for display
6print(dict(counts))

Output

[('a', 5), ('b', 2), ('r', 2)]
{'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1}
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.

  • (× 5
  • )× 5
  • "× 2
  • =× 2
  • _× 1
  • .× 1

More Python examples at level 5

← Python typing practice