Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse yaml into a list in python

I am required to use YAML for a project. I have a YAML file which I am using to populate a list in a Python program which interacts with the data.

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:

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.

like image 820
johnfk3 Avatar asked Oct 02 '15 21:10

johnfk3


People also ask

How can I parse a YAML file in Python?

We can read the YAML file using the PyYAML module's yaml. load() function. This function parse and converts a YAML object to a Python dictionary ( dict object). This process is known as Deserializing YAML into a Python.

Does Python have a built in YAML parser?

However, Python lacks built-in support for the YAML data format, commonly used for configuration and serialization, despite clear similarities between the two languages.

What is YAML dump?

Dumping YAML dump accepts the second optional argument, which must be an open text or binary file. In this case, yaml. dump will write the produced YAML document into the file. Otherwise, yaml. dump returns the produced document.

How do you represent a list in YAML?

Each element in the list is represented in YAML as a new line with the same indentation, starting with - followed by a space.


2 Answers

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

like image 112
woryzower Avatar answered Oct 13 '22 01:10

woryzower


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']

like image 21
Anthon Avatar answered Oct 13 '22 00:10

Anthon