ChainMap是dict的子类,拥有dict的所有功能, 感觉用它的地方吧???
from collections import ChainMap """ 相当于join两个dict的操作 """ # 示例1 dict1 = {"a": 1, "b": 2} dict2 = {"c": 3, "d": 4} chain_dict = ChainMap(dict1, dict2) for k, v in chain_dict.items(): print(k, v) ''' 打印结果: c 3 d 4 a 1 b 2 ''' print('-' * 50) # 示例2 dict1 = {"a": 1, "b": 2} dict2 = {"b": 3, "d": 4} chain_dict = ChainMap(dict1, dict2) for k, v in chain_dict.items(): print(k, v) ''' 打印结果: b只出现了一次,就是首次的值 b 2 d 4 a 1 ''' print('-' * 50) # 示例3 dict1 = {"a": 1, "b": 2} dict2 = {"c": 3, "d": 4} chain_dict = ChainMap(dict1, dict2) chain_dict.update({'e': 8}) for k,v in chain_dict.items(): print(k,v) ''' c 3 d 4 a 1 b 2 e 8 ''' print('-' * 50) # 示例4 dict1 = {"a": 1, "b": 2} dict2 = {"c": 3, "d": 4} chain_dict = ChainMap(dict1, dict2) print(chain_dict) # Remove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.' 感觉没啥用 item = chain_dict.popitem() print(item) # ('b', 2) # pop也只能弹出chain_map[0]中的元素,有点鸡 value = chain_dict.pop('a') print(value) #1 print(chain_dict) # ChainMap({}, {'c': 3, 'd': 4}) print('-' * 50) dict1 = {"a": 1, "b": 2} dict2 = {"c": 3, "d": 4} chain_dict = ChainMap(dict1, dict2) # new_chain_dict = chain_dict.new_child() # print(new_chain_dict) # ChainMap({}, {'a': 1, 'b': 2}, {'c': 3, 'd': 4}) , 这有啥用呀 # 在chain_map添加一个新的dict new_chain_dict = chain_dict.new_child({'name':'admin'}) print(new_chain_dict) # ChainMap({'name': 'admin'}, {'a': 1, 'b': 2}, {'c': 3, 'd': 4})