Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
706 views
in Technique[技术] by (71.8m points)

dictionary - Loop through a list of dictionaries in yaml file and update just a section of the file with python

I am trying to dynamically update a yaml file which contains a list of dicts. Below is an example of my original yaml file

images:
  - name: image1
    tag: v1
  - name: image2
    tag: v1

I would like to loop through images and only update image1's tag then write it to the yaml file. Below is the resulting file I would like

images:
  - name: image1
    tag: v2
  - name: image2
    tag: v1

I currently have a script that allows me to update and print the new dict, but I cannot get it to render within the yaml file. Below is my code example

#!/usr/env python
import yaml
 
image_file = yaml.load(open(file.yaml, "r"))

def update_dict(dict, path, value):
    dict_to_update = dict
    key_list = path.split(".")
    for k in key_list[:-1]:
        dict_to_update = dict_to_update[k]
    dict_to_update[key_list[-1]] = value

images = image_file['images']

for image in images:
    if image['name'] == 'image1':
        update_dict(image, "tag", "v2")
        print image
        #prints {'tag': 'v2', 'name': 'image1'}
        with open(file.yaml, "w") as file:
            yaml.dump(image, file)

This will completely overwrite file.yaml to result in

name: image1
tag: v2

Is there a way to only update a section of a yaml file dynamically? Or will I need to store the whole list of dicts, modify what is needed, then overwrite file.yaml with the new list of dicts?

question from:https://stackoverflow.com/questions/66047954/loop-through-a-list-of-dictionaries-in-yaml-file-and-update-just-a-section-of-th

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...