I am trying to dump a Python dictionary to YAML which has some strings as value fields.
import yaml
str1 = "hello"
str2 = "world"
mystr = "\"" + str1 + str(" ") + str2 + "\""
mydict = {"a" : mystr}
f = open("temp.yaml", "w")
yaml.dump(mydict, f, default_flow_style = False, \
explicit_start = "---", explicit_end = "...", encoding = 'UTF-8')
f.close()
the YAML I get is:
a: '"hello
world"'
Notice, the value "hello world" is spilling to the next line. I am using python 3.5 and YAML module version is 3.11
Can someone tell me how to make the YAML look like below?
a: "hello world"
The code is a bit sloppy but it will give the results you want.
The result will look like:
a: "Hello World"
If you want fine grain control over which string gets double (or single) quotes, you should use ruamel.yaml (disclaimer: I am the author of that package). It is an improved version of PyYAML, with many longstanding issues in PyYAML fixed.
With it you can do:
to get:
If you start out with a YAML document, things are even easier, you can just indicate you want to preserve these superfluous quotes: