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.

Accessing Values


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


d=D
a=A
b=B
c=C

Reodering


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


[{'a': 'A', 'c': 'C'}, {'b': 'B', 'c': 'D'}]
c=C

In [6]:
m.maps = list(reversed(m.maps))
print(m.maps)
print('c={}'.format(m['c']))


[{'b': 'B', 'c': 'D'}, {'a': 'A', 'c': 'C'}]
c=D

Updating Values


In [7]:
import collections
a = {'a':'A', 'c':'C'}
b = {'b':'B', 'c':'D'}
m = collections.ChainMap(a, b)
print(m.maps)


[{'a': 'A', 'c': 'C'}, {'b': 'B', 'c': 'D'}]

In [8]:
m['c'] ='E'
print(m.maps)


[{'a': 'A', 'c': 'E'}, {'b': 'B', 'c': 'D'}]

In [9]:
print(a)


{'a': 'A', 'c': 'E'}

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)


m1 before ChainMap({'a': 'A', 'c': 'C'}, {'b': 'B', 'c': 'D'})
m2 before ChainMap({}, {'a': 'A', 'c': 'C'}, {'b': 'B', 'c': 'D'})
m1 after ChainMap({'a': 'A', 'c': 'C'}, {'b': 'B', 'c': 'D'})
m2 after ChainMap({'c': 'E'}, {'a': 'A', 'c': 'C'}, {'b': 'B', 'c': 'D'})