Search code examples
pythonyamlpyyaml

How to save yaml key-values with the root key in Python?


I'm using Python to manipulate a yaml file. I'm trying to save a new file with key-value pairs including the key (I think that's what its called).

Let's say my yaml file looks like this:

info:
 - name: test
 version: 1.0
images:
 - name: myimage
 newtag: 1.0-beta

I can read the yaml file into a variable in Python with a simple:

with open('test.yaml', 'r') as f:
    data = yaml.load(f, Loader=yaml.FullLoader)
f.close()

I can save a new yaml file with just the "image" values with this:

with open('new.yaml', 'w') as outfile:
    yaml.dump(data.get("images"), outfile, default_flow_style=False)
outfile.close()

The output file looks like this:

 - name: myimage
 newtag: 1.0-beta

I'm trying to code it so that instead of the output file just having the 2 lines above, it also includes the "images:" key at the top. This new yaml file should be just like the original, but, with essentially no other key-values apart from "images:". I also realized that the values below "images:" are indented. I'm finding this tricky and help is appreciated.


Solution

  • If you want to output a single key-value pair, you need to give a dict with one entry:

    yaml.dump(dict(images=data.get("images")), outfile, default_flow_style=False)