使用 ruamel 在 yaml 中插入节点

inserting node in yaml with ruamel

我想打印以下布局:

extra: identifiers: biotools: - http://bio.tools/abyss

我正在使用此代码添加节点:

yaml_file_content['extra']['identifiers'] = {}<br> yaml_file_content['extra']['identifiers']['biotools'] = ['- http://bio.tools/abyss']

但是,相反,我得到了这个输出,它将工具封装在 [] 中:

extra: identifiers: biotools: ['- http://bio.tools/abyss']

我尝试过其他组合但没有用?

加载 YAML 文件后,它不再是 "yaml";它现在是一个 Python 数据结构, biotools 键的内容是 list:

>>> import ruamel.yaml as yaml
>>> data = yaml.load(open('data.yml'))
>>> data['extra']['identifiers']['biotools']
['http://bio.tools/abyss']

与任何其他 Python 列表一样,您可以 append 添加它:

>>> data['extra']['identifiers']['biotools'].append('http://bio.tools/anothertool')
>>> data['extra']['identifiers']['biotools']
['http://bio.tools/abyss', 'http://bio.tools/anothertool']

如果您打印出数据结构,您将获得有效的 YAML:

>>> print( yaml.dump(data))
extra:
  identifiers:
    biotools: [http://bio.tools/abyss, http://bio.tools/anothertool]

当然,如果出于某种原因您不喜欢该列表表示形式,您也可以获得语法上等效的形式:

>>> print( yaml.dump(data, default_flow_style=False))
extra:
  identifiers:
    biotools:
    - http://bio.tools/abyss
    - http://bio.tools/anothertool

- http://bio.tools/abyss 中的破折号表示一个序列元素,如果您以块样式转储 Python 列表,它会添加到输出中。

所以不要这样做:

yaml_file_content['extra']['identifiers']['biotools'] = ['- http://bio.tools/abyss']

你应该做的:

yaml_file_content['extra']['identifiers']['biotools'] = ['http://bio.tools/abyss']

然后强制以块样式输出所有复合元素:

yaml.default_flow_style = False

如果您想要更细粒度的控制,请创建一个 ruamel.yaml.comments.CommentedSeq 实例:

tmp = ruamel.yaml.comments.CommentedSeq(['http://bio.tools/abyss'])
tmp.fa.set_block_style()
yaml_file_content['extra']['identifiers']['biotools'] = tmp