
- 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.ChainMap
In Python, ChainMap class is used to convert multiple dictionaries or mappings into single unit. If no maps are specified, a single empty dictionary is provided so that a new chain always has at least one mapping.
The ChainMap() class is defined in Collections module. It is often much faster than creating a new dictionary.
Syntax
Following is the syntax of the Python ChainMap() −
collections.ChainMap(iterable1, iterable2, iterable3)
Parameters
This data-type accepts an iterables as a parameters
Return Value
This data-type returns a new ChainMap object, which maps multiple iterable.
Example
Following is an basic example of the Python ChainMap() −
# Python program to demonstrate # ChainMap from collections import ChainMap d1 = {'one': 1, 'two': 2} d2 = {'three': 3, 'four': 4} d3 = {'five': 5, 'six': 6} # Defining the chainmap c = ChainMap(d1, d2, d3) print(c)
Following is the output of the above code −
ChainMap({'one': 1, 'two': 2}, {'three': 3, 'four': 4}, {'five': 5, 'six': 6})
Using ChainMap for Nested Scope Simulation
The ChainMap() class can be used to simulate nested scopes and is useful in templating. It allows us to combine multiple dictionaries or mappings into a single unit, so we can search for an element across all dictionaries as if they were one. Instead of searching each dictionary individually, ChainMap checks each one in order of priority and stops as soon as it finds a match.
Example
In the following example ChainMap() with nested scopes −
from collections import ChainMap default_settings = {'theme': 'dark', 'font': 'Arial', 'size': 12} user_settings = {'theme': 'light', 'size': 14} # ChainMap gives priority to the first dictionary (user_settings) settings = ChainMap(user_settings, default_settings) print(settings['theme']) print(settings['font'])
Following is the output of the above code −
light Arial
Underlying Mappings in ChainMap
In the ChainMap class, the underlying mappings (dictionaries) are stored as a list. This list is accessible through the maps attribute, which allows you to directly view or modify the dictionaries being managed by the ChainMap.
Example
Here, is an example underlying mappings in ChainMap() −
from collections import ChainMap # Two dictionaries dict1 = {'a': 1, 'b': 2} dict2 = {'b': 3, 'c': 4} # Create a ChainMap combined = ChainMap(dict1, dict2) print(combined['b']) # Accessing the maps attribute print(combined.maps) # Updating the order of dictionaries in the ChainMap combined.maps = [dict2, dict1] print(combined['b'])
Following is the output of the above code −
2 [{'a': 1, 'b': 2}, {'b': 3, 'c': 4}] 3
Combining Multiple Lists Using ChainMap
The ChainMap() can also be used to convert multiple lists into single unit.
Example
Following is an example of using ChainMap() with list −
from collections import ChainMap list1 = ['a','b','c','d'] list2 = [1, 2, 3, 4] list3 = ['one','two','three'] chain_list = ChainMap(list1, list2, list3) print(chain_list)
Following is the output of the above code −
ChainMap(['a', 'b', 'c', 'd'], [1, 2, 3, 4], ['one', 'two', 'three'])
Access Operations in ChainMap
We can access all keys of the dictionaries in the ChainMap using keys() function. The values() function returns all the values of the dictionaries in ChainMap. maps() function is used to display keys with corresponding values of all the dictionaries in ChainMap.
Example
# keys(), values() and maps # importing collections for ChainMap operations import collections # initializing dictionaries dic1 = { 'Program1' : 'Python', 'Program2' : 'HTML' } dic2 = { 'Program3' : ' Java', 'Program4' : 'C' } # initializing ChainMap chain = collections.ChainMap(dic1, dic2) # printing chainMap using maps print ("All the ChainMap contents are : ") print (chain.maps) # printing keys using keys() print ("All keys of ChainMap are : ") print (list(chain.keys())) # printing keys using keys() print ("All values of ChainMap are : ") print (list(chain.values()))
Following is the output of the above code −
All the ChainMap contents are : [{'Program1': 'Python', 'Program2': 'HTML'}, {'Program3': ' Java', 'Program4': 'C'}] All keys of ChainMap are : ['Program3', 'Program4', 'Program1', 'Program2'] All values of ChainMap are : [' Java', 'C', 'Python', 'HTML']
Methods in ChainMap
Following are methods defined in the ChainMap() class −
Method | Function |
---|---|
new_child() | adds a new dictionary or iterable in the beginning of the ChainMap |
reversed() | reverses the relative ordering of dictionaries or iterable in the ChainMap |
Python ChainMap.new_child() Method
The new_child() method is used to add a new dictionary or iterable at the beginning of the ChainMap().
Example
In the following example we have added a new dictionary to the ChainMap() using new_child() −
from collections import ChainMap list1 = ['a','b','c','d'] list2 = [1, 2, 3, 4] list3 = ['one','two','three'] chain_list = ChainMap(list1, list2) print(chain_list) print(chain_list.new_child(list3))
Following is the output of the above code −
ChainMap(['a', 'b', 'c', 'd'], [1, 2, 3, 4]) ChainMap(['one', 'two', 'three'], ['a', 'b', 'c', 'd'], [1, 2, 3, 4])
Python ChainMap.reversed() Method
The reversed() method is used to reverse the dictionaries or iterables in the ChainMap.
Example
Following is an example of reversed() method in the ChainMap −
from collections import ChainMap # Define multiple lists list1 = ['a', 'b', 'c', 'd'] list2 = [1, 2, 3] list3 = ['one', 'two'] # Create a ChainMap with the first two lists chain_list = ChainMap(list1, list2) # Print the initial ChainMap print("Original ChainMap -", chain_list) # Reverse the order of maps in the original ChainMap (note: reversed() does not modify the list) reversed_maps = list(reversed(chain_list.maps)) # This creates a reversed list # Print the reversed order of maps (for demonstration) print("Reversed maps -", reversed_maps)
Following is the output of the above code −
Original ChainMap - ChainMap(['a', 'b', 'c', 'd'], [1, 2, 3]) Reversed maps - [[1, 2, 3], ['a', 'b', 'c', 'd']] Original maps after reversal attempt: [['a', 'b', 'c', 'd'], [1, 2, 3]]