SoFunction
Updated on 2025-04-14

Summary of the use of defaultdict in basic Python syntax

Python's defaultdict is a special dictionary type provided in the collections module. It has similar functions to ordinary dictionaries, but has a key difference: when accessing a non-existent key, the defaultdict will not throw a KeyError exception, but will automatically create a default value for the key. This feature makes it easier to handle situations where new keys need to be initialized.

createdefaultdictTo usedefaultdictFirst of all, we need tocollectionsModule imports it:

from collections import defaultdict

Then you can create adefaultdictInstance, pass in a callable object as the default_factory parameter.
This callable object determines the default value type that should be returned when accessing non-existent keys.
For example:

  • useintAsdefault_factoryWill return integer0
  • uselistAsdefault_factoryWill return to an empty list[]
  • usesetAsdefault_factoryWill return an empty collectionset()
  • Use custom functions asdefault_factoryThe default value will be determined based on the return value of the function.

Example 1

from collections import defaultdict

bag = ['apple', 'orange', 'cherry', 'apple','apple', 'cherry', 'blueberry']
count = defaultdict(int)  # Use int as default_factoryprint(f"\n > > > > > > count:\n {count}")
print(f"\n > > > > > > type(count):\n {type(count)}")

for fruit in bag:
    count[fruit] += 1
print(f"\n > > > > > > count:\n {count}")

Output:

 > > > > > > count:
 defaultdict(<class 'int'>, {})

 > > > > > > type(count):
 <class ''>

 > > > > > > count:
 defaultdict(<class 'int'>, {'apple': 3, 'orange': 1, 'cherry': 2, 'blueberry': 1})

In this example, when operating on a non-existent key, defaultdict will automatically assign a default value of 0 to the key and allow direct incremental operation.

Example 2

from collections import defaultdict

names = [('group1', 'Alice'), ('group2', 'Bob'), ('group1', 'Charlie')]
grouped_names = defaultdict(list)
print(f"\n > > > > > > grouped_names:\n {grouped_names}")
print(f"\n > > > > > > type(grouped_names):\n {type(grouped_names)}")

for group, name in names:
    grouped_names[group].append(name)

print(f"\n > > > > > > grouped_names:\n {grouped_names}")

Output:

 > > > > > > grouped_names:
 defaultdict(<class 'list'>, {})

 > > > > > > type(grouped_names):
 <class ''>

 > > > > > > grouped_names:
 defaultdict(<class 'list'>, {'group1': ['Alice', 'Charlie'], 'group2': ['Bob']})

In this example, the names are grouped according to the first element. If using a normal dictionary, additional logic is needed to check and initialize each new group.

This is the end of this article about the use of defaultdict in the basic grammar of Python. For more related Python defaultdict content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!