In [1]:
a = {'x': 1, 'z': 3}
b = {'y': 2, 'z': 4}
# 需在两 dict 中执行查找操作 (先从 a 中找,若是找不到,再在 b 中找)
from collections import ChainMap
c = ChainMap(a,b)
print(c['x'])
print(c['y'])
print(c['z'])
In [3]:
len(c)
Out[3]:
In [4]:
list(c.keys())
Out[4]:
In [5]:
list(c.values())
Out[5]:
In [12]:
c['z'] = 10
c['w'] = 80
del c['x']
In [7]:
c_old = ChainMap(a,b)
In [8]:
c_old
Out[8]:
In [ ]:
In [9]:
type(c_old)
Out[9]:
In [13]:
values = ChainMap()
values['x'] = 1
# Add a new mapping
values = values.new_child()
values['x'] = 2
# Add a new mapping
values = values.new_child()
values['x'] = 3
In [14]:
values
Out[14]:
In [15]:
values['x']
Out[15]:
In [16]:
# Discard last mapping
values = values.parents
values['x']
Out[16]:
In [17]:
# Discard last mapping
values = values.parents
values['x']
Out[17]:
In [18]:
values
Out[18]:
In [22]:
a = {'x':1,'z':3}
b = {'y':2,'z':4}
merged = dict(b)
merged.update(a)
In [23]:
print(merged['x'],'\n\n',merged['y'],'\n\n',merged['z'])
In [25]:
a['x'] = 19
merged['x']
Out[25]:
In [26]:
a = {'x': 1, 'z': 3}
b = {'y': 2, 'z': 4}
merged = ChainMap(a,b)
In [27]:
merged['x']
Out[27]:
In [28]:
a['x'] = 43
merged['x'] # Notice change to merged dict
Out[28]: