chainmap用法
时间: 2024-03-06 20:43:00 浏览: 21
ChainMap是Python中的一个集合类,它可以将多个字典或映射组合在一起,形成一个单独的可迭代对象。下面是ChainMap的基本用法和parents、new_child()方法的演示:
1. ChainMap的基本用法
```python
from collections import ChainMap
# 定义三个字典
dict1 = {'x': 1, 'y': 2}
dict2 = {'y': 3, 'z': 4}
dict3 = {'z': 5, 'w': 6}
# 将三个字典组合成一个ChainMap对象
chain_map = ChainMap(dict1, dict2, dict3)
# 输出ChainMap对象的键值对
for key, value in chain_map.items():
print(key, value)
```
输出结果为:
```
z 4
y 2
w 6
x 1
```
可以看到,ChainMap对象的键值对是按照字典的顺序依次排列的,如果有重复的键,ChainMap对象会优先使用第一个字典中的键值对。
2. parents方法的用法
ChainMap对象有一个parents属性,它可以返回一个新的ChainMap对象,其中只包含当前ChainMap对象中除第一个字典以外的所有字典。下面是一个例子:
```python
from collections import ChainMap
# 定义三个字典
dict1 = {'x': 1, 'y': 2}
dict2 = {'y': 3, 'z': 4}
dict3 = {'z': 5, 'w': 6}
# 将三个字典组合成一个ChainMap对象
chain_map = ChainMap(dict1, dict2, dict3)
# 获取除第一个字典以外的所有字典
parents = chain_map.parents
# 输出parents对象的键值对
for key, value in parents.items():
print(key, value)
```
输出结果为:
```
z 5
y 3
w 6
```
可以看到,parents对象中只包含了除第一个字典以外的所有字典。
3. new_child方法的用法
ChainMap对象还有一个new_child()方法,它可以返回一个新的ChainMap对象,其中包含当前ChainMap对象中的第一个字典和新的字典。下面是一个例子:
```python
from collections import ChainMap
# 定义三个字典
dict1 = {'x': 1, 'y': 2}
dict2 = {'y': 3, 'z': 4}
dict3 = {'z': 5, 'w': 6}
# 将三个字典组合成一个ChainMap对象
chain_map = ChainMap(dict1, dict2, dict3)
# 添加一个新的字典
new_dict = {'a': 7, 'b': 8}
new_chain_map = chain_map.new_child(new_dict)
# 输出new_chain_map对象的键值对
for key, value in new_chain_map.items():
print(key, value)
```
输出结果为:
```
b 8
a 7
z 4
y 2
x 1
```
可以看到,new_chain_map对象中包含了当前ChainMap对象中的第一个字典和新的字典。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)