简体   繁体   English

将 YAML 嵌套到 Python 中的嵌套字典

[英]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 推荐的解决方案相反:

  • is safe with uncontrolled YAML input.不受控制的 YAML 输入是安全的。
  • it supports the latest YAML standard (version 1.2, published 2009)它支持最新的 YAML 标准(1.2 版,2009 年发布)
  • it is faster on most platforms (at least on macOS/Windows/Linux where wheels are available)它在大多数平台上都更快(至少在有轮子的 macOS/Windows/Linux 上)

Disclaimer: I am the author of ruamel.yaml免责声明:我是ruamel.yaml的作者

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM