[英]Nested YAML to nested dictionary in Python
I don't know how to get a nested dictionary from a nested YAML file.我不知道如何从嵌套的 YAML 文件中获取嵌套的字典。
YAML file looks like this : YAML 文件如下所示:
device1:
device_type: cisco_ios
ip: s1
username: admin
password: 123456
secret: 123456
port: 22
device2:
device_type: cisco_ios
ip: s2
username: admin
password: 123456
secret: 123456
port: 22
Dictionary should look like this:字典应该是这样的:
net_devices = {
'device_1': {
'device_type': 'cisco_ios',
'ip': 's1',
'username': 'admin',
'password': '123456',
'secret': '123456',
'port': 22,
},
'device_2': {
'device_type': 'cisco_ios',
'ip': 's2',
'username': 'admin',
'password': '123456',
'secret': '123456',
'port': 22,
}
}
How can I do this in Python?我怎样才能在 Python 中做到这一点?
Just install PyYAML https://pypi.org/project/PyYAML/只需安装 PyYAML https://pypi.org/project/PyYAML/
Then :然后 :
import yaml
yaml_as_python_dict = yaml.load(yaml_as_string_or_bytes)
https://pyyaml.org/wiki/PyYAML https://pyyaml.org/wiki/PyYAML
Install ruamel.yaml
from pypi从 pypi 安装
ruamel.yaml
from ruamel.yaml import YAML
yaml = YAML(typ='safe')
with open('your_yaml_file.yaml') as fp:
data = yaml.load(fp)
Contrary to the solution recommended by @glenfant:与@glenfant 推荐的解决方案相反:
Disclaimer: I am the author of ruamel.yaml
免责声明:我是
ruamel.yaml
的作者
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.