将yaml解析为python中的列表

时间:2015-10-02 21:26:44

标签: python list yaml pyyaml

我需要将YAML用于项目。我有一个YAML文件,我用它来填充Python程序中与数据交互的列表。

我的数据如下:

maven-compiler-plugin

我需要python代码来迭代这个YAML文件并填充这样的列表:

Employees:
    custid: 200
    user: Ash
        - Smith
        - Cox

我知道我必须打开文件,然后将数据存储在变量中,但我无法弄清楚如何在列表中单独输入每个元素。理想情况下,我想使用append函数,所以我不必每次都确定我的'用户'大小。

2 个答案:

答案 0 :(得分:2)

with open("employees.yaml", 'r') as stream:
    out = yaml.load(stream)
    print out['Employees']['user']

应该已经为您提供了用户列表。另请注意,您的yaml在用户节点之后缺少一个破折号

答案 1 :(得分:2)

YAML sequences are translated to python lists for you (at least when using PyYAML or ruamel.yaml), so you don't have to append anything yourself.

In both PyYAML and ruamel.yaml you either hand a file/stream to the load() routine or you hand it a string. Both:

import ruamel.yaml

with open('input.yaml') as fp:
    data = ruamel.yaml.load(fp)

and

import ruamel.yaml

with open('input.yaml') as fp:
    str_data = fp.read()
data = ruamel.yaml.load(str_data)

do the same thing.

Assuming you corrected your input to:

Employees:
    custid: 200
    user:
    - Ash
    - Smith
    - Cox

you can print out data:

{'Employees': {'custid': 200, 'user': ['Ash', 'Smith', 'Cox']}}

and see that the list is already there and can be accessed via normal dict lookups: data['Employees']['user']