ChainMap

  • groups multiple dicts or other mappings together to create a single, updateable view

Initialization

  • the last map is the root, the first map is the current context
In [ ]:
from collections import ChainMap

a = {'Name': 'Lin', 'Age': 39}
b = {'maker': 'Honda', 'year': 2016}
cm = ChainMap(a, b) # ChainMap({'Name': 'Lin', 'Age': 39}, {'maker': 'Honda', 'year': 2016})

# access an element by key
cm['Name']

Methods

In [ ]:
d = cm.new_child() # Create nested child context
print(d) # ChainMap({}, {'Name': 'Lin', 'Age': 39}, {'maker': 'Honda', 'year': 2016})

d.maps[1] # {'Name': 'Lin', 'Age': 39}, get the second map
d.maps[0] = {'ID': 970196897} # assign a map to a child

print(d) # ChainMap({'ID': 970196897}, {'Name': 'Lin', 'Age': 39}, {'maker': 'Honda', 'year': 2016})

# parents, returning a new ChainMap containing all of the maps in the current instance except the first one
print(d.parents) # ChainMap({'Name': 'Lin', 'Age': 39}, {'maker': 'Honda', 'year': 2016})

d['x'] = 1 # add key and value to the current context
print(d) # ChainMap({'ID': 970196897, 'x': 1}, {'Name': 'Lin', 'Age': 39}, {'maker': 'Honda', 'year': 2016})
del d['x'] 
print(d) # ChainMap({'ID': 970196897}, {'Name': 'Lin', 'Age': 39}, {'maker': 'Honda', 'year': 2016})

Built-in Functions

In [ ]:
list(d) # all nested keys
print('Name' in d) # True
len(d) # 5
d.items() # ItemsView(ChainMap({'ID': 970196897}, {'Name': 'Lin', 'Age': 39}, {'maker': 'Honda', 'year': 2016}))
d = dict(d) # Flatten into a regular dictionary
print(d) # {'maker': 'Honda', 'year': 2016, 'Name': 'Lin', 'Age': 39, 'ID': 970196897}