It is very easy to read a YAML file in Python as a combination of dict and lists using PyYAML. However, the YAML format does not require PyYAML to read the keys of any dict in the YAML file to be read in the order it appears in the file. In addition, Python dict also does not have any order to the keys in it. However, in certain situations it might be necessary to read the keys in YAML in the order they appear in the file. This can be done by using the yamlordereddictloader.
- Installing this Python package is easy using pip:
$ sudo pip install yamlordereddictloader
- Read YAML files by providing the loader from this package to PyYAML:
import yaml import yamlordereddictloader with open("foobar.yaml") as f: yaml_data = yaml.load(f, Loader=yamlordereddictloader.Loader)
This returns the data in the YAML file as a combination of lists and OrderedDict (instead of dict). So, almost all of the rest of the your code should work the same as before after this change.
Tried with: yamlordereddictloader 0.4 and Ubuntu 16.04