Python 101: `defaultdict(int)` vs `defaultdict(list)`

Let’s compare defaultdict(int) and defaultdict(list) by using examples that demonstrate their differences and appropriate use cases.

1. defaultdict(int) – Used for Counting Occurrences:

When you use defaultdict(int), it initializes missing keys with 0 (the default for int). This is commonly used when you need to count occurrences of elements.

Example Code for defaultdict(int):

from collections import defaultdict

# Using defaultdict(int) to count occurrences
map_n = defaultdict(int)

nums = [1, 2, 1, 3, 2, 4, 1]

# Count the frequency of each number
for n in nums:
    map_n[n] += 1

# Convert defaultdict to regular dict for display purposes
print(dict(map_n))

Output for defaultdict(int):

{1: 3, 2: 2, 3: 1, 4: 1}

Explanation:

  • defaultdict(int): Each key that doesn’t exist is initialized to 0. As you iterate through nums, the count for each key (number) is incremented.
  • Example use case: Counting the frequency of elements in a list.

2. defaultdict(list) – Used for Grouping Elements:

When you use defaultdict(list), it initializes missing keys with an empty list []. This is useful for grouping or collecting multiple values under a single key.

Example Code for defaultdict(list):

from collections import defaultdict

# Using defaultdict(list) to group elements
map_n = defaultdict(list)

nums = [1, 2, 1, 3, 2, 4, 1]

# Group numbers by their value
for n in nums:
    map_n[n].append(n)

# Convert defaultdict to regular dict for display purposes
print(dict(map_n))

Output for defaultdict(list):

{1: [1, 1, 1], 2: [2, 2], 3: [3], 4: [4]}

Explanation:

  • defaultdict(list): Each missing key is initialized to an empty list []. As you iterate through nums, each value is appended to the list associated with that key.
  • Example use case: Grouping elements (e.g., collecting all occurrences of the same element in separate lists).

Key Differences:

Feature defaultdict(int) defaultdict(list)
Default value 0 (for int) [] (empty list)
Use case Counting occurrences of elements Grouping elements under the same key
Example operation Increment the value: map_n[n] += 1 Append to the list: map_n[n].append(n)
Example result for list {1: 3, 2: 2, 3: 1, 4: 1} {1: [1, 1, 1], 2: [2, 2], 3: [3], 4: [4]}

Summary:

  • defaultdict(int) is best used when you want to count how many times something appears, like counting words or elements in a list.
  • defaultdict(list) is best used when you want to collect multiple values under the same key, such as grouping elements or building an adjacency list.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *