Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading