Parse yaml into a list in python

johnfk3 picture johnfk3 · Oct 2, 2015 · Viewed 25.6k times · Source

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.

Answer

woryzower picture woryzower · Oct 2, 2015
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