The ChainMap class manages a sequence of dictionaries, and searches through them in the order they are given to find values associated with keys. A ChainMap makes a good “context” container, since it can be treated as a stack for which changes happen as the stack grows, with these changes being discarded again as the stack shrinks.
In [1]:
import collections
a = {'a':'A', 'c':'C'}
b = {'b':'B', 'd':'D'}
m = collections.ChainMap(a, b)
for k, v in m.items():
print('{}={}'.format(k, v))
In [5]:
import collections
a = {'a':'A', 'c':'C'}
b = {'b':'B', 'c':'D'}
m = collections.ChainMap(a, b)
print(m.maps)
print('c={}'.format(m['c']))
In [6]:
m.maps = list(reversed(m.maps))
print(m.maps)
print('c={}'.format(m['c']))
In [7]:
import collections
a = {'a':'A', 'c':'C'}
b = {'b':'B', 'c':'D'}
m = collections.ChainMap(a, b)
print(m.maps)
In [8]:
m['c'] ='E'
print(m.maps)
In [9]:
print(a)
In [10]:
import collections
a = {'a':'A', 'c':'C'}
b = {'b':'B', 'c':'D'}
m1 = collections.ChainMap(a, b)
m2 = m1.new_child()
print('m1 before', m1)
print('m2 before', m2)
m2['c']='E'
print('m1 after', m1)
print('m2 after', m2)