defaultdict
Anonymous contributor
Published Jan 26, 2024
Contribute to Docs
In Python, defaultdict is a data type that belongs to the collections
module. It is a dictionary subclass that is used to return a dictionary-like object.
Syntax
collections.defaultdict(default_factory)
default_factory
: It gives the default value for the dictionary object.
Example
The following example demonstrates the defaultdict
data type:
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
Codebyte Example
Run the following codeblock and explore more about the defaultdict
data type:
All contributors
- Anonymous contributor
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
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours