Python also contains a container called “ChainMap” which encapsulates many dictionaries into one unit. ChainMap is member of module “collections“.
Operations on ChainMap
Access Operations
1. keys() :- This function is used to display all the keys of all the dictionaries in ChainMap.
2. values() :- This function is used to display values of all the dictionaries in ChainMap.
3. maps :- This function is used to display keys with corresponding values of all the dictionaries in ChainMap.
python - Sample - python code :
python programming - Output :
All the ChainMap contents are :
[{'b': 2, 'a': 1}, {'c': 4, 'b': 3}]
All keys of ChainMap are :
['a', 'c', 'b']
All values of ChainMap are :
[1, 4, 2]
Note : Notice the key named “b” exists in both dictionaries, but only first dictionary key is taken as key value of “b”. Ordering is done as the dictionaries are passed in function.
Manipulating Operations
1. new_child() :- This function adds a new dictionary in the beginning of the ChainMap.
2. reversed() :- This function reverses the relative ordering of dictionaries in the ChainMap.
python - Sample - python code :
python programming - Output :
All the ChainMap contents are :
[{'b': 2, 'a': 1}, {'b': 3, 'c': 4}]
Displaying new ChainMap :
[{'f': 5}, {'b': 2, 'a': 1}, {'b': 3, 'c': 4}]
Value associated with b before reversing is : 2
Value associated with b after reversing is : 3