Python defaultdict
In Python, defaultdict is a data type that belongs to the collections module. It is a dictionary subclass that automatically provides a default value for missing keys.
Syntax
collections.defaultdict(default_factory)
Parameters:
default_factory: A callable (such as a function or type likeint,list,set) that provides the default value for missing keys. If set toNone, aKeyErroris raised when accessing a missing key.
Return value:
Returns a defaultdict object, which behaves like a dictionary but creates default values for missing keys using the specified default_factory.
Example 1: Using a Custom Function
The following example demonstrates the defaultdict data type with a custom function as default_factory argument:
from collections import defaultdictdef default_value():return "Not Declared"myDefaultDict = defaultdict(default_value)myDefaultDict["first"] = 100myDefaultDict["second"] = 90print(myDefaultDict["first"])print(myDefaultDict["second"])print(myDefaultDict["third"])
Here is the output for the above code:
10090Not Declared
Example 2: Using Built-in Callables
This example demonstrates defaultdict with built-in types (int, list, str, set) as the default_factory:
from collections import defaultdictintDefaultDict = defaultdict(int)listDefaultDict = defaultdict(list)strDefaultDict = defaultdict(str)setDefaultDict = defaultdict(set)print(intDefaultDict[0])print(listDefaultDict['zero'])print(strDefaultDict['0'])print(setDefaultDict['a'])
Here is the output of the above code:
0[]set()
Example 3: Working with Lists
This example shows how list as default_factory allows appending to keys that don’t yet exist:
from collections import defaultdictmyDefaultDict = defaultdict(list)myDefaultDict['apple'].append(1)# myDefaultDict['apple'] does not exist so it defaults to empty list [],# then 1 is appended to it.myDefaultDict['orange'] = 2#The empty list [] is replaced by integer 2 here.print(myDefaultDict['apple'])print(myDefaultDict['orange'])
Here is the output of the above code:
[1]2
Codebyte Example
Run the following codeblock and explore more about the defaultdict data type:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours