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