C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Display: We can display values by accessing each key, or we can display the entire counter by passing it to the print method.
Python program that uses Counter
from collections import Counter
# Create new counter.
freqs = Counter()
# Add to the counter based on ranges of numbers.
for i in range(0, 10):
freqs[i] += 1
for i in range(0, 5):
freqs[i] += 1
for i in range(0, 2):
freqs[i] += 1
# Display counter contents.
for i in range(0, 10):
print(f"Value at {i} is {freqs[i]}")
# The counter can be displayed directly.
print(freqs)
Output
Value at 0 is 3
Value at 1 is 3
Value at 2 is 2
Value at 3 is 2
Value at 4 is 2
Value at 5 is 1
Value at 6 is 1
Value at 7 is 1
Value at 8 is 1
Value at 9 is 1
Counter({0: 3, 1: 3, 2: 2, 3: 2, 4: 2, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1})
Python program that uses Counter with strings
from collections import Counter
freqs = Counter()
print(freqs)
# Three birds are born.
freqs["bird"] += 1
freqs["bird"] += 1
freqs["bird"] += 1
print(freqs)
# One bird was killed.
freqs["bird"] -= 1
print(freqs)
# Four birds were counted.
freqs["bird"] = 4
print(freqs)
Output
Counter()
Counter({'bird': 3})
Counter({'bird': 2})
Counter({'bird': 4})