简体   繁体   English

ruamel.yaml:修改dump()以在开始时添加额外的“-”

[英]ruamel.yaml: modify dump() to add extra '-' at the very start

I'm using ruamel.yaml library to dump a dictionary into a yaml file. 我正在使用ruamel.yaml库将字典转储到yaml文件中。 However it does not behave the way I'd like it to. 但是,它的行为并不符合我的期望。

How could I get: 我如何获得:

---
- a: 
    - foo: bar
    - bar: foo

instead of: 代替:

a:
    - foo: bar
    - bar: foo

with yaml.dump() yaml.dump()

I'm extracting the data from: 我正在从中提取数据:

data = {
    'a': [
         {'foo':'bar'},
         {'bar':'foo'}
       ]
     }

Any other library with the same functionality is open for proposal. 具有相同功能的任何其他库均已开放供投标。

What you are looking for is setting explicit_start = True on the YAML instance. 您正在寻找的是在YAML实例上设置explicit_start = True In addition you need to make the top-level a list if you want - a instead of just a on the second line: 此外,您需要做的顶级如果你想有一个列表- a ,而不是只是a在第二行:

import sys
import ruamel.yaml

yaml_str = """\
---
-a:
    -foo: bar
    -bar: foo
"""

data = [{
    'a': [
         {'foo':'bar'},
         {'bar':'foo'}
       ]
     }]

yaml = ruamel.yaml.YAML()
yaml.explicit_start = True
yaml.dump(data, sys.stdout)

gives: 给出:

---
- a:
  - foo: bar
  - bar: foo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM