{'web': {'ProtocolEnabled': True, 'Port': 443}, 'kvm': {'ProtocolEnabled': True, 'Port': 7578}, 'webTimeOut': 30, 'kvmTimeOut': 30} 嵌套字典的key='ProtocolEnabled,如果对应的value 是True或False,映射修改为Open或close
时间: 2023-12-25 21:04:00 浏览: 22
将嵌套字典中的 'ProtocolEnabled' 的值为 True 改为 'Open',将值为 False 改为 'Close',可以使用以下代码实现:
```python
nested_dict = {'web': {'ProtocolEnabled': True, 'Port': 443}, 'kvm': {'ProtocolEnabled': True, 'Port': 7578}, 'webTimeOut': 30, 'kvmTimeOut': 30}
def update_protocol_status(data):
if isinstance(data, dict):
for key, value in data.items():
if isinstance(value, dict):
update_protocol_status(value)
elif key == 'ProtocolEnabled':
if value:
data[key] = 'Open'
else:
data[key] = 'Close'
return data
updated_dict = update_protocol_status(nested_dict)
print(updated_dict)
```
运行以上代码,输出结果为:
```
{'web': {'ProtocolEnabled': 'Open', 'Port': 443}, 'kvm': {'ProtocolEnabled': 'Open', 'Port': 7578}, 'webTimeOut': 30, 'kvmTimeOut': 30}
```
注意:此代码会修改原始的嵌套字典。如果你不想修改原始字典,可以在函数内部创建一个新的字典进行操作。
相关推荐
![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)