If you want to preserve your original YAML layout and quoting, then you cannot generally do that with pyyaml without a lot of effort.
With ruamel.yaml
(disclaimer: I am the author of that package) this is much simpler, but you still need to do something for the top-level indentation by two spaces (using the transform
parameter):
import sys
import ruamel.yaml
yaml_str = """\
---
'Croatia':
population: 4600000
capital: Zagreb
"""
def indent_data(s):
return s.replace('\n', '\n ')
yaml = ruamel.yaml.YAML()
# yaml.indent(mapping=4, sequence=4, offset=2)
yaml.preserve_quotes = True
yaml.explicit_start = True
data = yaml.load(yaml_str)
data['Croatia']['continent'] = 'Europe'
yaml.dump(data, sys.stdout, transform=indent_data)
gives:
---
'Croatia':
population: 4600000
capital: Zagreb
continent: Europe
Any comments in the original document would be preserved in the output, but EOL comments might shift because of the extra indentation.