Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to read YAML file in Python with ordered keys

📅 2017-Nov-23 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ ordereddict, python, yaml ⬩ 📚 Archive

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.

$ sudo pip install yamlordereddictloader
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

© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘📧