defaultdict

Anonymous contributor's avatar
Anonymous contributor
Anonymous contributor's avatar
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 defaultdict
def default_value():
return "Not Declared"
myDefaultDict = defaultdict(default_value)
myDefaultDict["first"] = 100
myDefaultDict["second"] = 90
print(myDefaultDict["first"])
print(myDefaultDict["second"])
print(myDefaultDict["third"])

Here is the output for the above code:

100
90
Not Declared

Codebyte Example

Run the following codeblock and explore more about the defaultdict data type:

us
Visit us
code
Hide code
Code
Output
Hide output
Hide output
Loading...

All contributors

Looking to contribute?

Learn Python on Codecademy