简体   繁体   English

将yaml解析为python中的列表

[英]Parse yaml into a list in python

I am required to use YAML for a project. 我需要为项目使用YAML。 I have a YAML file which I am using to populate a list in a Python program which interacts with the data. 我有一个YAML文件,该文件用于填充与数据进行交互的Python程序中的列表。

My data looks like this: 我的数据如下所示:

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

I need the python code to iterate over this YAML file and populate a list like this: 我需要python代码遍历此YAML文件并填充如下列表:

list_of_Employees = ['Ash', 'Smith' 'Cox']

I know I must open the file and then store the data in a variable, but I cannot figure out how to enter each element separately in a list. 我知道必须先打开文件,然后将数据存储在变量中,但是我无法弄清楚如何在列表中分别输入每个元素。 Ideally I would like to use the append function so I don't have to determine my 'user' size every time. 理想情况下,我想使用append函数,因此不必每次都确定“用户”的大小。

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

Should already give you list of users.Also note that your yaml missing one dash after user node 应该已经为您提供了用户列表。还请注意,您的Yaml用户节点后缺少一个破折号

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. YAML序列会为您翻译成python列表(至少在使用PyYAMLruamel.yaml时 ),因此您不必自己添加任何内容。

In both PyYAML and ruamel.yaml you either hand a file/stream to the load() routine or you hand it a string. 在PyYAML和ruamel.yaml中,您要么将文件/流传递给load()例程,要么将其传递给字符串。 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'] 并看到该列表已经存在,可以通过常规的dict查询访问: data['Employees']['user']

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

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