ChainMap in Python


The ChainMap is used to encapsulates the dictionaries into single unit.

The ChainMapis a standard library class, which is located in the collections module.

To use it at first we need to import it the collections standard library module.

import collections

In this section we will see some functions of the ChainMap class

The maps and keys() values() functions

The maps is used to display all key value pairs of all the dictionaries from the ChainMap. The keys() method will return the keys from the ChainMap, and values() method returns all the values() of different keys from the ChainMap.

Example Code

import collections as col
con_code1 = {'India' : 'IN', 'China' : 'CN'}
con_code2 = {'France' : 'FR', 'United Kingdom' : 'GB'}
chain = col.ChainMap(con_code1, con_code2)
print("Initial Chain: " + str(chain.maps))
print('The keys in the ChainMap: ' + str(list(chain.keys())))
print('The values in the ChainMap: ' + str(list(chain.values())))

Output

Initial Chain: [{'India': 'IN', 'China': 'CN'}, {'France': 'FR', 'United Kingdom': 'GB'}]
The keys in the ChainMap: ['China', 'United Kingdom', 'India', 'France']
The values in the ChainMap: ['CN', 'GB', 'IN', 'FR']

The new_child() and reversed method

The new_child() method is used to add another dictionary object to the ChainMap at the beginning. And the reversed method is also can be used to ChainMap to reverse the order of the key-value pairs.

Example Code

import collections as col
con_code1 = {'India' : 'IN', 'China' : 'CN'}
con_code2 = {'France' : 'FR', 'United Kingdom' : 'GB'}
code = {'Japan' : 'JP'}
chain = col.ChainMap(con_code1, con_code2)
print("Initial Chain: " + str(chain.maps))
chain = chain.new_child(code)    #Insert New Child
print("Chain after Inserting new Child: " + str(chain.maps))
chain.maps = reversed(chain.maps)
print("Reversed Chain: " + str(chain))

Output

Initial Chain: [{'India': 'IN', 'China': 'CN'}, {'France': 'FR', 'United Kingdom': 'GB'}]
Chain after Inserting new Child: [{'Japan': 'JP'}, {'India': 'IN', 'China': 'CN'}, {'France': 'FR', 'United Kingdom': 'GB'}]
Reversed Chain: ChainMap({'France': 'FR', 'United Kingdom': 'GB'}, {'India': 'IN', 'China': 'CN'}, {'Japan': 'JP'})

Updated on: 30-Jul-2019

647 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements