Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python yaml update preserving order and comments

Im inserting a key into Yaml using python but I would like to preserve order and comments in the yaml

#This Key is used for identifying Parent tests
    ParentTest:
       test:
         JOb1: myjob
         name: testjob
         arrive: yes

Now Im using below code to insert new key

params['ParentTest']['test']['new_key']='new value'
yaml_output=yaml.dump(pipeline_params, default_flow_style=False)

How to preserve the exact order and comments ?

Below arrive moved up but I want to preserve order & comments as well

output is :

 ParentTest:
       test:
         arrive: yes
         JOb1: myjob
         name: testjob
like image 668
shiv455 Avatar asked Nov 19 '17 21:11

shiv455


People also ask

Does Yaml guarantee order?

I've found in a StackOverflow question, and a pyyaml PR that the yaml spec does not guarantee an order of keys in a mapping. I found in the PyYAML PR that it automatically sorts the keys when you run . dump() , so the YAML file itself is already in a different order.

How do I add comments to a Yaml file in Python?

In order to add comments to a YAML file, you simply have to use the # (hashtag symbol) at the start of the line.

What is Yaml Safe_load?

Loading a YAML Document Safely Using safe_load() safe_load(stream) Parses the given and returns a Python object constructed from the first document in the stream. safe_load recognizes only standard YAML tags and cannot construct an arbitrary Python object.

What does greater than mean in Yaml?

What does greater than mean in YAML? The greater than sign notation, also referred to as “folded block”: folded: > This block of text will be the value of 'folded', but this. time, all newlines will be replaced with a single space. Blank lines, like above, are converted to a newline character.


1 Answers

pyyaml cannot keep comments, but ruamel does.

Try this:

doc = ruamel.yaml.load(yaml, Loader=ruamel.yaml.RoundTripLoader)
doc['ParentTest']['test']['new_key'] = 'new value'
print ruamel.yaml.dump(doc, Dumper=ruamel.yaml.RoundTripDumper)

The order of keys will also be preserved.

Edit: Look at Anthon's answer from 2020: https://stackoverflow.com/a/59659659/93745

like image 169
tinita Avatar answered Oct 03 '22 22:10

tinita