Some examples on working with YAML (‘YAML Ain’t Markup Language’) in Python3. In the examples, I am using PyYAML version 5.2 which can be installed using pip3 install pyyaml.

Emit a Python object as YAML

The dump method is used to serialize a Python object into a YAML stream. In the following example, we emit the Python dictionary as a string:

import yaml

d = {
  'string' : 'string',
  'list': ['item-1', 'item-2',],  
  'nested-dictionary' : { 
    'key-1' : 'value-1',
    'key-2' : 'value-2',
  'True' : True,
  'False' : False,
  'None' : None,

print(yaml.dump(d, sort_keys=False))

This code will output the following:

string: string
- item-1
- item-2
  key-1: value-1
  key-2: value-2
'True': true
'False': false
None: null

Dump will automatically sort the keys for you. In the previous example, I used sort_keys=False to turn that off.

Write a Python object as YAML to a file:

We can also use the dump method to write a Python object to a file:

import yaml

d = { 'key' : 'value' }

with open("example.yaml", "w") as fh:  
  yaml.dump(d, fh)

This example results in the following YAML file:

[root@said ~]$ more example.yaml 
key: value

Create a Python object from a YAML string

Using the load method, we can turn YAML into a Python object:

import yaml

yaml_string = """
  capital: Paris
  capital: Rome
  - item 1
  - item 2
  - item 3  

python_object = yaml.load(yaml_string, Loader=yaml.SafeLoader)


This will output the following:

{'France': {'capital': 'Paris'}, 'Italy': {'capital': 'Rome'}, 'list_of_items': ['item 1', 'item 2', 'item 3']}

In case we want to use the load methods to generate a Python object from a file, we can use something like this:

import yaml

yaml_file = "example.yaml" # key: value

with open(yaml_file, "r") as fh:
  python_object = yaml.load(fh, Loader=yaml.SafeLoader)


The output of the script:

{'key': 'value'}

The loader is relatively new and described here.

Instead of specifying the loader as an argument, we can also use the following methods to directly indicate what method to use to load the YAML:

- yaml.safe_load
- yaml.full_load
- yaml.unsafe_load

Using YAML in jinja

To use YAML data inside a Jinja template, you could do something like this:

import yaml
from jinja2 import Template

yaml_string  = '''
- hostname: ny01
- hostname: ny02

routers = yaml.full_load(yaml_string)

template = Template('''

{% for router in routers %}
hostname {{ router['hostname'] }}
set interfaces lo0 unit 0 family inet address {{ router['mgmt-ip'] }} primary
{% endfor %}


print(template.render(routers = routers))

Running the example script produces the following:

set system host-name ny01
set interfaces lo0 unit 0 family inet address primary

set system host-name ny02
set interfaces lo0 unit 0 family inet address primary

Some YAML resources:
PyYAML documentation
PyYAML github
Online YAML Parser
onlineyamltools can do a number of things:

  • Validate YAML
  • Turn YAML into JSON
  • Make the YAML pretty