[Python] Ruamel.yaml, extra dict items getting adding past comment? [duplicate]

Discussão em 'Python' iniciado por Stack, Agosto 13, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to use ruamel.yaml to update some configuration files. While this does work, I can't seem to get it entirely right. Specifically, I'm trying to add key/value to an existing dict, with the intention of having it added at the end. Demo code:

    from ruamel.yaml import YAML
    yaml = YAML()
    yaml.preserve_quotes = True
    yaml.indent(offset=2)

    raw = """---
    # Some config file..
    # This is the main clients config
    clients:
    foobar1:
    name: foo Bar 1
    auth: false
    count: 1290
    barboz:
    name: BarraBoz
    auth: true
    count: 19


    ##############################
    # here be the other items #
    ##############################
    archives:
    ral1: false
    ral2: true
    customers:
    - None
    - Foo
    - 5
    bazo:
    new: key

    # More junk below
    inventory:
    - egg
    - shell
    """

    vanhelst = {"adfs": 124423423, "123": "adsfadsfasdf", "name": "Dirk Van helst"}


    data = yaml.load(raw)
    data["clients"].insert(len(data["clients"]), "vanhelst", vanhelst)

    # Write to file
    with open("/tmp/out.yml", "w") as f:
    yaml.dump(data, f)


    The gives me:

    # Some config file..
    # This is the main clients config
    clients:
    foobar1:
    name: foo Bar 1
    auth: false
    count: 1290
    barboz:
    name: BarraBoz
    auth: true
    count: 19


    ##############################
    # here be the other items #
    ##############################
    vanhelst:
    adfs: 124423423
    '123': adsfadsfasdf
    name: Dirk Van helst
    archives:
    ral1: false
    ral2: true
    customers:
    - None
    - Foo
    - 5
    bazo:
    new: key

    # More junk below
    inventory:
    - egg
    - shell


    But my intention is to end up with this:

    # Some config file..
    # This is the main clients config
    clients:
    foobar1:
    name: foo Bar 1
    auth: false
    count: 1290
    barboz:
    name: BarraBoz
    auth: true
    count: 19
    vanhelst:
    adfs: 124423423
    '123': adsfadsfasdf
    name: Dirk Van helst


    ##############################
    # here be the other items #
    ##############################
    archives:
    ral1: false
    ral2: true
    customers:
    - None
    - Foo
    - 5
    bazo:
    new: key

    # More junk below
    inventory:
    - egg
    - shell


    Inserting it at any other place does work, but I'm looking to add it at the end.

    inserting does add it at the functional end, but it is still after the comment that belongs to the next key....

    Continue reading...

Compartilhe esta Página