Help us understand the problem. What is going on with this article?

PyYAMLで順序を保持して読み込む

More than 5 years have passed since last update.

PyYAMLについてメモ

PyYAMLでYamlファイルを読み込んだ場合、デフォルトだと通常のDictionaryとして読み込むため、
ファイルの順序が保証されない。

例えばこんな感じのYamlファイルがあったとして、

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

普通にyaml.loadして出力すると

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))

こんな感じになる。

実行結果
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

ファイルに記載されている通りの順序で読み込みたい場合は、OrderedDictとして読み込むようにしてやる

yaml_load.py
import yaml
from collections import OrderedDict

# これを追加する
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))

これで順序を保持して読み込める。

実行結果
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

この辺を参考にした

以上

tkyaji
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした