Reputation: 7764
My Yaml looks like this
server-params:
environment: prod
artifact_version: 0.0.0.*
I would like to insert another key named jobs and expected output as below,
server-params:
environment: prod
artifact_version: 0.0.0.*
jobs: ['test','test2']
I have tried this
jobs_list =['test','test2']
params = yaml.safe_load(params)
params['server-params']['jobs']=jobs_list
yaml.dump(params, default_flow_style=False)
output:
server-params:
environment: prod
artifact_version: 0.0.0.*
jobs:
- test
- test2
Upvotes: 0
Views: 85
Reputation: 25789
Lose the default_flow_style
parameter (or set it to True
) if you want your lists not to expand in your YAML, e.g.:
test_yaml = """
server-params:
environment: prod
artifact_version: 0.0.0.*
"""
jobs_list = ['test', 'test2']
params = yaml.safe_load(test_yaml)
params['server-params']['jobs'] = jobs_list
print(yaml.dump(params))
Which will yield:
server-params: artifact_version: 0.0.0.* environment: prod jobs: [test, test2]
If you want to keep your YAML ordered, tho, it will depend on the module you're using for all things YAML. If you're using ruamel.yaml
(and if you're not, you should) use ruamel.yaml.RoundTripLoader
as a Loader
and ruamel.yaml.RoundTripDumper
as a Dumper
. If you're using PyYAML
you can use the yamlordereddictloader
module.
Upvotes: 1