Search code examples
pythonpyyamlruamel.yaml

inserting node in yaml with ruamel


I would like to have printed the following layout:

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

I'm using this code to add nodes:

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

But, instead, I'm getting this output, that encapsulates the tool in []:

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

I have tried other combinations but didn't work?


Solution

  • The dash in - http://bio.tools/abyss indicates a sequence element and is added on output if you dump a Python list in block style.

    So instead of doing:

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

    you should be doing:

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

    and then force the output of all composite elements in block style using:

    yaml.default_flow_style = False
    

    If you want finer grained control, create a ruamel.yaml.comments.CommentedSeq instance:

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