English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Initializing a variable-sized array in C

ChainMap is used to encapsulate dictionaries into a single unit.

ChainMap is a standard library class located incollectionsmodule.

Firstly, to use it, we need to import it from the standard library module of collections.

import collections

In this section, we will see some features of the ChainMap class

mapping andkeys() values()method

The mapping is used to display all key-value pairs of all dictionaries in the ChainMap. Thiskeys()The method will return keys from ChainMap, and this method is fromvalues()Returns allvalues()Different keys.

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 Result

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']

new_child() and reverse method

The new_child() method is used to add another dictionary object to the ChainMap at the beginning. The reverse method can also be used with ChainMap to reverse the order of 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 Result

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'})