代码之家  ›  专栏  ›  技术社区  ›  ypriverol

使用ruamel在yaml中插入节点

  •  1
  • ypriverol  · 技术社区  · 7 年前

    我想打印以下布局:

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

    我使用以下代码添加节点:

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

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

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

    我尝试过其他组合,但没有成功?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Anthon    7 年前

    冲刺 - 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
    
        2
  •  1
  •   larsks    7 年前

    加载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