<jupyter_start><jupyter_text>Often in Python, we want to count the number of occurrences in a data structure.<jupyter_code>people = ["John", "Dave", "Martin", "John", "Brad", "John", "Dave"]

# manually
counts = {}
for person in people:
  if person in counts:
    counts[person] += 1
  else:
    counts[person] = 1

counts
# introduce defaultdict
from collections import defaultdict

counts = defaultdict(int)
for person in people:
  counts[person] += 1

counts
# issubclass(defaultdict, dict)

from collections import Counter

counts = Counter(people)

counts
# issubclass(Counter, dict)

counts.most_common(2)
counts.subtract(['John', 'Brad'])
counts
# applying to a tuple
Counter((1,2,3,4,2,3,6,8,3,4,6,4,5,5,5,5,5,5,5))

# apply to a set (1 per element)
Counter({1,2,3,4,2,3,6,8,3,4,6,4,5,5,5,5,5,5,5})<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.15550239234449761, 'fraction_numerical': 0.05143540669856459, 'mean_word_length': 5.917355371900826, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '638246', 'license': 'MIT', 'n_tokens_mistral': 339, 'n_tokens_neox': 329, 'n_words': 81, 'path': 'python-standard-library/collections/defaultdict and Counter.ipynb', 'repo_name': 'bugbytes-io/notebooks', 'size': '836'}