[PYTHON] Preserve and read order in PyYAML

Note about PyYAML

When reading a Yaml file with PyYAML, it will be read as a normal Dictionary by default, so The order of the files is not guaranteed.

For example, if you have a Yaml file like this

data.yml


aaa:
  a1: 1
  a2: 2
  a3: 3
bbb:
  b1: 1
  b2: 2
  b3: 3
ccc:
  c1: 1
  c2: 2
  b3: 3

If you normally yaml.load and output

yaml_load.py


import yaml

data = yaml.load(file("data.yml"))

for k1, v1 in data.items():
    for k2, v2 in v1.items():
        print("%s - %s - %s" % (k1, k2, v2))

It looks like this.

Execution result


aaa - a1 - 1
aaa - a3 - 3
aaa - a2 - 2
bbb - b1 - 1
bbb - b2 - 2
bbb - b3 - 3
ccc - c2 - 2
ccc - c1 - 1
ccc - b3 - 3

If you want to read in the order described in the file, read it as OrderedDict.

yaml_load.py


import yaml
from collections import OrderedDict

#Add this
yaml.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
    lambda loader, node: OrderedDict(loader.construct_pairs(node)))

data = yaml.load(file("data.yml"))

for k1, v1 in data.items():
    for k2, v2 in v1.items():
        print("%s - %s - %s" % (k1, k2, v2))

Now you can keep the order and read.

Execution result


aaa - a1 - 1
aaa - a2 - 2
aaa - a3 - 3
bbb - b1 - 1
bbb - b2 - 2
bbb - b3 - 3
ccc - c1 - 1
ccc - c2 - 2
ccc - b3 - 3

Around here Was referred to

that's all

Recommended Posts

Preserve and read order in PyYAML
Ignore # line and read in pandas
Create and read messagepacks in Python
Read and write JSON files in Python
Read DXF in python
Read the csv file and display it in the browser
Read and write single precision floating point in Python
Read and write NFC tags in python using PaSoRi
Read XBRL and easily visualize changes in business performance
Natural order in python
Reference order of class variables and instance variables in "self. Class variables" in Python
Tips for coding short and easy to read in Python
Read json in C # and convert to dictionary type (forced)
Extract array elements and indexes in descending order with numpy
Read and write csv file
Read Euler's formula in Python
Read and write a file
Read Namespace-specified XML in Python
Read Outlook emails in Python
Stack and Queue in Python
Write and read a file
Unittest and CI in Python
Read Fortran output in python