Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Collections.UserDict in Python
Next article icon

Defaultdict in Python

Last Updated : 09 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, defaultdict is a subclass of the built-in dict class from the collections module. It is used to provide a default value for a nonexistent key in the dictionary, eliminating the need for checking if the key exists before using it.

Key Features of defaultdict:

  • When we access a key that doesn’t exist in the dictionary, defaultdict automatically creates it and assigns it a default value based on a function we provide.
  • We need to specify the default value type by passing a function (like int, list or set) when initializing the defaultdict.

Example:

Python
from collections import defaultdict  d = defaultdict(list)  d['fruits'].append('apple') d['vegetables'].append('carrot') print(d)  print(d['juices']) 

Output
defaultdict(<class 'list'>, {'fruits': ['apple'], 'vegetables': ['carrot']}) [] 

Explanation: This code creates a defaultdict with a default value of an empty list. It adds elements to the ‘fruits’ and ‘vegetables’ keys. When trying to access the ‘juices’ key, no KeyError is raised, and an empty list is returned since it doesn’t exist in the dictionary.

Syntax of DefaultDict in Python

defaultdict(default_factory)

Parameters:

  • default_factory: A function returning the default value for the dictionary defined. If this argument is absent then the dictionary raises a KeyError.

Return Value: It returns a dictionary-like object that automatically provides a default value for missing keys, based on the specified callable, instead of raising a KeyError.

How Does defaultdict Work?

When a defaultdict is created, you specify a factory function that will provide the default value for new keys. This factory function could be int, list, str, or any other callable object. For example:

  • Using int: If you use int as the factory function, the default value will be 0 (since int() returns 0).
  • Using list: If you use list as the factory function, the default value will be an empty list ([]).
  • Using str: If you use str, the default value will be an empty string (”).

What is default factory in Python dict?

It is a function returning the default value for the dictionary defined. If this argument is absent then the dictionary raises a KeyError.

Python
from collections import defaultdict       # Defining the dict and passing lambda as default_factory argument d = defaultdict(lambda: "Not Present") d["a"] = 1 d["b"] = 2  print(d["a"]) print(d["b"]) print(d["c"]) 

Output
1 2 Not Present 

Use Cases for defaultdict

1. Using List as Default Factory

When the list class is passed as the default_factory argument, then a defaultdict is created with the values that are list.

Python
from collections import defaultdict  d = defaultdict(list)  for i in range(5):     d[i].append(i)      print("Dictionary with values as list:") print(d) 

Output
Dictionary with values as list: defaultdict(<class 'list'>, {0: [0], 1: [1], 2: [2], 3: [3], 4: [4]}) 

Explanation: This example demonstrates the use of list as the default factory. A defaultdict is created with list, which means any missing key will automatically have an empty list as its value. The loop appends the value of i to the list of the corresponding key.

2. Using int Default Factory

When the int class is passed as the default_factory argument, then a defaultdict is created with default value as zero.

Python
from collections import defaultdict   d = defaultdict(int)   a = [1, 2, 3, 4, 2, 4, 1, 2]    for i in a:      d[i] += 1       print(d) 

Output
defaultdict(<class 'int'>, {1: 2, 2: 3, 3: 1, 4: 2}) 

Explanation: This example uses int as the default factory. int() returns 0, so missing keys will have a default value of 0. The loop counts the occurrences of each number in the list a and updates the dictionary accordingly.

3. Using str Default Factory

When the str class is passed as the default_factory argument.

Python
from collections import defaultdict  # Using str as the factory function sd = defaultdict(str) sd['greeting'] = 'Hello' print(sd) 

Output
defaultdict(<class 'str'>, {'greeting': 'Hello'}) 

Explanation: This example uses str as the default factory. str() returns an empty string, so missing keys will have an empty string as their default value. A value (‘Hello‘) is explicitly set for the key ‘greeting‘.

Python defaultdict Type for Handling Missing Keys

Defaultdict adds one writable instance variable and one method in addition to the standard dictionary operations. The instance variable is the default_factory parameter and the method provided is __missing__.

This function is used to provide the default value for the dictionary. It takes default_factory as an argument and if this argument is None, a KeyError is raised otherwise it provides a default value for the given key. This method is basically called by the __getitem__() method of the dict class when the requested key is not found. __getitem__() raises or return the value returned by the __missing__(). method.

Python
from collections import defaultdict    d = defaultdict(lambda: "Not Present") d["a"] = 1 d["b"] = 2  print(d.__missing__('a')) print(d.__missing__('d')) 

Output
Not Present Not Present 

Explanation:

  • The defaultdict is initialized with a lambda function that returns “Not Present” for missing keys.
  • When the key ‘a‘ is accessed, its value is returned (1), and __missing__ is not called.
  • When the key ‘d‘ is accessed (which does not exist), __missing__ is triggered, and the default value “Not Present” is returned.


Next Article
Collections.UserDict in Python

N

nikhilaggarwal3
Improve
Article Tags :
  • Python
  • Python Programs
  • Python collections-module
Practice Tags :
  • python

Similar Reads

  • Python Collections Module
    The collection Module in Python provides different types of containers. A Container is an object that is used to store different objects and provide a way to access the contained objects and iterate over them. Some of the built-in containers are Tuple, List, Dictionary, etc. In this article, we will
    13 min read
  • Namedtuple in Python
    Python supports a type of container dictionary called "namedtuple()" present in the module "collections". In this article, we are going to see how to Create a NameTuple and operations on NamedTuple. What is NamedTuple in Python?In Python, NamedTuple is present inside the collections module. It provi
    8 min read
  • Deque in Python
    A deque stands for Double-Ended Queue. It is a data structure that allows adding and removing elements from both ends efficiently. Unlike regular queues, which are typically operated on using FIFO (First In, First Out) principles, a deque supports both FIFO and LIFO (Last In, First Out) operations.
    6 min read
  • ChainMap in Python
    Python contains a container called "ChainMap" which encapsulates many dictionaries into one unit. ChainMap is member of module "collections". Example: # Python program to demonstrate # ChainMap from collections import ChainMap d1 = {'a': 1, 'b': 2} d2 = {'c': 3, 'd': 4} d3 = {'e': 5, 'f': 6} # Defin
    3 min read
  • Python | Counter Objects | elements()
    Counter class is a special type of object data-set provided with the collections module in Python3. Collections module provides the user with specialized container datatypes, thus, providing an alternative to Python's general-purpose built-ins like dictionaries, lists, and tuples. Counter is a sub-c
    6 min read
  • OrderedDict in Python
    An OrderedDict is a dictionary subclass that remembers the order in which keys were first inserted. The only difference between dict() and OrderedDict() lies in their handling of key order in Python. OrderedDict vs dict in PythonNote: Starting from Python 3.7, regular dictionaries (dict) also mainta
    10 min read
  • Defaultdict in Python
    In Python, defaultdict is a subclass of the built-in dict class from the collections module. It is used to provide a default value for a nonexistent key in the dictionary, eliminating the need for checking if the key exists before using it. Key Features of defaultdict:When we access a key that doesn
    6 min read
  • Collections.UserDict in Python
    An unordered collection of data values that are used to store data values like a map is known as Dictionary in Python. Unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized. Note: For mo
    2 min read
  • Collections.UserList in Python
    Python Lists are array-like data structure but unlike it can be homogeneous. A single list may contain DataTypes like Integers, Strings, as well as Objects. List in Python are ordered and have a definite count. The elements in a list are indexed according to a definite sequence and the indexing of a
    2 min read
  • Collections.UserString in Python
    Strings are the arrays of bytes representing Unicode characters. However, Python does not support the character data type. A character is a string of length one. Example: C/C++ Code # Python program to demonstrate # string # Creating a String # with single Quotes String1 = 'Welcome to the Geeks Worl
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences