
- Python - Home
- Python - Overview
- Python - History
- Python - Features
- Python vs C++
- Python - Hello World Program
- Python - Application Areas
- Python - Interpreter
- Python - Environment Setup
- Python - Virtual Environment
- Python - Basic Syntax
- Python - Variables
- Python - Data Types
- Python - Type Casting
- Python - Unicode System
- Python - Literals
- Python - Operators
- Python - Arithmetic Operators
- Python - Comparison Operators
- Python - Assignment Operators
- Python - Logical Operators
- Python - Bitwise Operators
- Python - Membership Operators
- Python - Identity Operators
- Python - Operator Precedence
- Python - Comments
- Python - User Input
- Python - Numbers
- Python - Booleans
- Python - Control Flow
- Python - Decision Making
- Python - If Statement
- Python - If else
- Python - Nested If
- Python - Match-Case Statement
- Python - Loops
- Python - for Loops
- Python - for-else Loops
- Python - While Loops
- Python - break Statement
- Python - continue Statement
- Python - pass Statement
- Python - Nested Loops
- Python Functions & Modules
- Python - Functions
- Python - Default Arguments
- Python - Keyword Arguments
- Python - Keyword-Only Arguments
- Python - Positional Arguments
- Python - Positional-Only Arguments
- Python - Arbitrary Arguments
- Python - Variables Scope
- Python - Function Annotations
- Python - Modules
- Python - Built in Functions
- Python Strings
- Python - Strings
- Python - Slicing Strings
- Python - Modify Strings
- Python - String Concatenation
- Python - String Formatting
- Python - Escape Characters
- Python - String Methods
- Python - String Exercises
- Python Lists
- Python - Lists
- Python - Access List Items
- Python - Change List Items
- Python - Add List Items
- Python - Remove List Items
- Python - Loop Lists
- Python - List Comprehension
- Python - Sort Lists
- Python - Copy Lists
- Python - Join Lists
- Python - List Methods
- Python - List Exercises
- Python Tuples
- Python - Tuples
- Python - Access Tuple Items
- Python - Update Tuples
- Python - Unpack Tuples
- Python - Loop Tuples
- Python - Join Tuples
- Python - Tuple Methods
- Python - Tuple Exercises
- Python Sets
- Python - Sets
- Python - Access Set Items
- Python - Add Set Items
- Python - Remove Set Items
- Python - Loop Sets
- Python - Join Sets
- Python - Copy Sets
- Python - Set Operators
- Python - Set Methods
- Python - Set Exercises
- Python Dictionaries
- Python - Dictionaries
- Python - Access Dictionary Items
- Python - Change Dictionary Items
- Python - Add Dictionary Items
- Python - Remove Dictionary Items
- Python - Dictionary View Objects
- Python - Loop Dictionaries
- Python - Copy Dictionaries
- Python - Nested Dictionaries
- Python - Dictionary Methods
- Python - Dictionary Exercises
- Python Arrays
- Python - Arrays
- Python - Access Array Items
- Python - Add Array Items
- Python - Remove Array Items
- Python - Loop Arrays
- Python - Copy Arrays
- Python - Reverse Arrays
- Python - Sort Arrays
- Python - Join Arrays
- Python - Array Methods
- Python - Array Exercises
- Python File Handling
- Python - File Handling
- Python - Write to File
- Python - Read Files
- Python - Renaming and Deleting Files
- Python - Directories
- Python - File Methods
- Python - OS File/Directory Methods
- Python - OS Path Methods
- Object Oriented Programming
- Python - OOPs Concepts
- Python - Classes & Objects
- Python - Class Attributes
- Python - Class Methods
- Python - Static Methods
- Python - Constructors
- Python - Access Modifiers
- Python - Inheritance
- Python - Polymorphism
- Python - Method Overriding
- Python - Method Overloading
- Python - Dynamic Binding
- Python - Dynamic Typing
- Python - Abstraction
- Python - Encapsulation
- Python - Interfaces
- Python - Packages
- Python - Inner Classes
- Python - Anonymous Class and Objects
- Python - Singleton Class
- Python - Wrapper Classes
- Python - Enums
- Python - Reflection
- Python Errors & Exceptions
- Python - Syntax Errors
- Python - Exceptions
- Python - try-except Block
- Python - try-finally Block
- Python - Raising Exceptions
- Python - Exception Chaining
- Python - Nested try Block
- Python - User-defined Exception
- Python - Logging
- Python - Assertions
- Python - Built-in Exceptions
- Python Multithreading
- Python - Multithreading
- Python - Thread Life Cycle
- Python - Creating a Thread
- Python - Starting a Thread
- Python - Joining Threads
- Python - Naming Thread
- Python - Thread Scheduling
- Python - Thread Pools
- Python - Main Thread
- Python - Thread Priority
- Python - Daemon Threads
- Python - Synchronizing Threads
- Python Synchronization
- Python - Inter-thread Communication
- Python - Thread Deadlock
- Python - Interrupting a Thread
- Python Networking
- Python - Networking
- Python - Socket Programming
- Python - URL Processing
- Python - Generics
- Python Libraries
- NumPy Tutorial
- Pandas Tutorial
- SciPy Tutorial
- Matplotlib Tutorial
- Django Tutorial
- OpenCV Tutorial
- Python Miscellenous
- Python - Date & Time
- Python - Maths
- Python - Iterators
- Python - Generators
- Python - Closures
- Python - Decorators
- Python - Recursion
- Python - Reg Expressions
- Python - PIP
- Python - Database Access
- Python - Weak References
- Python - Serialization
- Python - Templating
- Python - Output Formatting
- Python - Performance Measurement
- Python - Data Compression
- Python - CGI Programming
- Python - XML Processing
- Python - GUI Programming
- Python - Command-Line Arguments
- Python - Docstrings
- Python - JSON
- Python - Sending Email
- Python - Further Extensions
- Python - Tools/Utilities
- Python - GUIs
- Python Advanced Concepts
- Python - Abstract Base Classes
- Python - Custom Exceptions
- Python - Higher Order Functions
- Python - Object Internals
- Python - Memory Management
- Python - Metaclasses
- Python - Metaprogramming with Metaclasses
- Python - Mocking and Stubbing
- Python - Monkey Patching
- Python - Signal Handling
- Python - Type Hints
- Python - Automation Tutorial
- Python - Humanize Package
- Python - Context Managers
- Python - Coroutines
- Python - Descriptors
- Python - Diagnosing and Fixing Memory Leaks
- Python - Immutable Data Structures
- Python Useful Resources
- Python - Questions & Answers
- Python - Interview Questions & Answers
- Python - Online Quiz
- Python - Quick Guide
- Python - Reference
- Python - Cheatsheet
- Python - Projects
- Python - Useful Resources
- Python - Discussion
- Python Compiler
- NumPy Compiler
- Matplotlib Compiler
- SciPy Compiler
Python collections.defaultdict
The Python defaultdict() is a container, which is similar to the dictionaries. It is present in the collection module. It is a subclass of the dictionary class which returns a dictionary as object.
The functionality of the both dictionaries and defaultdict are similar, the only difference is the defualtdict does not raise a KeyError. It provides a default value for the key which does not exists.
Syntax
Following is a syntax of the Python defaultdict() class −
defaultdict(default_factory)
Parameters
Following is the parameters accepted by this class −
- default_factory : This is a function which returns a default value for the defined dictionary . If this argument is not passed than the function raises a KeyError.
Return Value
This class returns a <collections.defaultdict> object.
Example
Following is an basic example of the Python defaultdict() class −
from collections import defaultdict def default(): return 'Key not found' dic1 = defaultdict(default) dic1[1] = 'one' dic1[2] = 'two' dic1[3] = 'Three' print(dic1) print(dic1[5])
Following is the output of the above code −
defaultdict(<function default at 0x000002040ACC8A40>, {1: 'one', 2: 'two', 3: 'Three'}) Key not found
Using defaultdict() with __missing__()
The __missing__() method is used to define the behavior of default_factory that is passed as an argument in the defaultdict(). If the default_factory is None this method generates a KeyError.
Example
Following is an example of the defaultdict() with __missing__() method −
from collections import defaultdict def default(): return 'Key not found' #defined defaultdict dic1 = defaultdict(default) dic1[1] = 'Python' dic1[2] = 'Java' dic1[3] = 'C++' print(dic1) #__missing__() function var1 = dic1.__missing__(1) print(var1)
Following is the output of the above code −
defaultdict(<function default at 0x000001F92A5F8A40>, {1: 'Python', 2: 'Java', 3: 'C++'}) Key not found
List as default_factory
In defaultdict(), we can pass the list as a default_factory. When we try to find the value of the key which is not present in the dictionary it will return an empty list.
Example
Here, we have defined a list of tuple and each tuple containing two values, keys and values. And we have passed the list as argument in the defaultdict() function and appended items into the dictionary −
# Python program to demonstrate # defaultdict from collections import defaultdict s = [('Python', 90), ('Java', 85), ('Python', 75), ('C++', 80), ('Java', 120)] dict1 = defaultdict(list) for k, v in s: dict1[k].append(v) sorted(dict1.items()) print(dict1) print("Key is not present in the dictionary :",dict1['html'])
Following is the output of the above code −
defaultdict(<class 'list'>, {'Python': [90, 75], 'Java': [85, 120], 'C++': [80]}) []
Integer Value as default_factory
In defaultdict(), when we can pass int as an argument, it makes the function countable. When we try to find a key which is not present it will return zero.
Example
Here, we have append the characters into dictionary and when we found the key value which is not present in the dictionary resulted 0 −
from collections import defaultdict var1 = 'Hello' dict1 = defaultdict(int) for k in var1: dict1[k] += 1 sorted(dict1.items()) print(dict1) #Value of key which is not found in dictionary print("Key Value :", dict1['k'])
Following is the output of the above code −
defaultdict(<class 'int'>, {'H': 1, 'e': 1, 'l': 2, 'o': 1}) Key Value : 0