A defaultdict simplifies counting by supplying a value when a new key is accessed. Instead of checking whether each number already exists, defaultdict(int) starts missing counts at zero. section 4.3.2
Counting numbers
Use it to count values in a sequence: counts = defaultdict(int); for number in numbers: counts[number] += 1. This removes the explicit if/else initialization step. section 4.3.2
from collections import defaultdict #1
def get_number_with_highest_count(counts):
max_count = 0
for number, count in counts.items():
if count > max_count:
max_count = count
number_with_highest_count = number
return number_with_highest_count
def most_frequent(numbers):
counts = defaultdict(int) #2
for number in numbers:
counts[number] += 1 #3
return get_number_with_highest_count(counts)
Compare the explicit dictionary check with defaultdict(int), which makes the counting loop shorter and clearer. section 4.3.2
For complete counting solutions, Counter can replace the defaultdict loop; defaultdict is the focused tool when you want controlled default values while building a mapping. section 4.3.2


