Notice that a YAML object has minimal syntax, all data
that is related has the same indentation level, and
key/value pairs are used to store data. YAML can also
represent a list by using the - character to identify
elements, as in the following example of IP addresses.
Click here to view code image
---
addresses:
- ip: 172.16.0.2
netmask: 255.255.255.0 - ip: 172.16.0.3
netmask: 255.255.255.0 - ip: 172.16.0.4
netmask: 255.255.255.0
To work with YAML in Python, you need to install and
import the PyYaml module. Once you import it into your
code, you can convert YAML to Python objects and back
again. YAML objects are converted to dictionaries, and
YAML lists automatically become Python lists. The two
functions that perform this magic are yaml.load to
convert from YAML objects into Python and
yaml.dump to convert Python objects back to YAML.
Just as in the other data examples, you can load a YAML
file and then pass it to yaml.load to work its magic. The
latest PyYaml module requires that you add an argument
to tell it which loader you want to use. This is a security
precaution so that your code will not be vulnerable to
arbitrary code execution from a bad YAML file. Here is
what the code looks like:
Click here to view code image
import yaml
with open("yaml_sample.yaml") as data:
yaml_sample = data.read()