17

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.

Anthon
  • 69,918
  • 32
  • 186
  • 246
johnfk3
  • 469
  • 2
  • 5
  • 15
  • 1
    Possible duplicate of [Parsing a YAML file in Python, and accessing the data?](http://stackoverflow.com/questions/8127686/parsing-a-yaml-file-in-python-and-accessing-the-data) – idjaw Oct 02 '15 at 21:27

2 Answers2

11
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

woryzower
  • 956
  • 3
  • 15
  • 22
  • 1
    Thank you, The missing dash was causing the problem – johnfk3 Oct 05 '15 at 17:30
  • 1
    On newer versions of Python, you have to use `safe_load` instead of `load` otherwise you'll get this error: ` YAMLLoadWarning: calling yaml.load() without Loader=... is deprecated, as the default Loader is unsafe. Please read https://msg.pyyaml.org/load for full details.` – Raleigh L. Aug 11 '22 at 04:30
  • 1
    @RaleighL. or add required positional argument 'Loader', e.g. `Loader=yaml.FullLoader` – msoutopico May 31 '23 at 05:56
7

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

Anthon
  • 69,918
  • 32
  • 186
  • 246