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.
SyntaxFollowing is the syntax of the Python ChainMap() −
collections.ChainMap(iterable1, iterable2, iterable3)Parameters
This data-type accepts an iterables as a parameters
Return ValueThis data-type returns a new ChainMap object, which maps multiple iterable.
ExampleFollowing 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.
ExampleIn 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 ArialUnderlying 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.
ExampleHere, 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}] 3Combining Multiple Lists Using ChainMap
The ChainMap() can also be used to convert multiple lists into single unit.
ExampleFollowing 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() MethodThe new_child() method is used to add a new dictionary or iterable at the beginning of the ChainMap().
ExampleIn 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.
ExampleFollowing 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]]
python_modules.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4