Search code examples
pythonfileioyamlpyyaml

writing Yaml file in python with no new line


Let's say I have the following snippet :

import yaml
Key = ["STAGE0", "STAGE1"]
dict = {}
dict[Key[0]] = [' ']
dict[Key[1]] = [' ']
dict[Key[0]][0]="HEY" 
dict[Key[0]][0]="WHY newline?"
with open("SUMMARY.YAML", "w") as file_yaml:
    yaml.dump(dict, file_yaml)

The output SUMMARY.YAML file looks like this :

STAGE0:
- WHY newline?
STAGE1:
- ' '

However I need to save them, in the following desired format :

STAGE0: WHY newline?
STAGE1: ' '

I am unable to get this output


Solution

  • You're creating a much more complex structure than you need, full of lists and references, just create the dict directly if you can

    data = {
        "STAGE0": "value0",    # single value
        "STAGE1": ["value1"],  # value in list
    }
    
    >>> print(yaml.dump(data))
    STAGE0: value0
    STAGE1:
    - value1
    

    or if you're amending in possible steps, just add the keys and values directly

    data = {}
    
    if True:
        data["STAGE0"] = "value0"
    if True:
        data["STAGE1"] = "value1"
    

    Finally, if you do create lists, .append() is likely a much better choice to add values rather than trying to create all the indicies initially

    try:
        data[key].append(value)
    except KeyError:
        data[key] = [value]