Saturday 20 March 2021

ChainMap in Python

 

ChainMap is used to group multiple dicts together to create a single view. It is present in Collections module.

The underlying dictionaries or mappings are stored in a list. This list can accessed using the maps attribute.

Required Key is searched through all the mappings or dictionaries in the ChainMap until it is found. Raises KeyError if the key is not found in any of the mappings.

 

Creating ChainMap

ChainMap can be created using built-in ChainMap( ) function:

from collections import ChainMap

d1 = {"a":1, "b":2,"c":3}

d2 = {"b":5,"d":6}

chainMap = ChainMap(d1, d2)

print(chainMap)

 


Write, update and delete operations only operate on first mapping. Consider the below code:

from collections import ChainMap

d1 = {"a":1, "b":2,"c":3}

d2 = {"b":5,"d":6}

chainMap = ChainMap(d1, d2)

chainMap["b"] = 4

print(chainMap.maps)

 

 

Trying to update the value of the existing key in the dict other than first dict in the ChainMap results in creating new key-value in the first dict as shown below:

from collections import ChainMap

d1 = {"a":1, "b":2,"c":3}

d2 = {"b":5,"d":6}

chainMap = ChainMap(d1, d2)

chainMap["d"] = 4

print(chainMap.maps)

 

Because ChainMap doesn’t allow update, write and delete operations on dicts ohter than first dict.




12 comments: