如何将 yaml 文件读取为字典并使用 python 更新值

How to read the yaml file as dictionary and update value using python

我需要编写函数来读取 YAML 文件并更新特定值。 YAML文件是字典,

sample :
    test_example:
    parent:
      attribute_1: 2
      attribute_2: 2
    parent2:
      childList:
        - group: 2
          type: "test"
          track_int:
            - key_1: 3
              key_2: 25
              state: present
          state: present
        - group: 4
          typr: "old"
          track_int:
            - key_1: 3
              key_2: 25
              state: present
          state: present

现在我需要编写函数来传递密钥,它应该替换特定值的值 例如 - 将 test_example["parent2"]["childList"][0]["group"] 更新为 4 并将 test_example["parent"]["attribute_2"] 更新为 5

我该怎么做?

如果您想按原样保留输入文件的其余部分,包括 "test""old" 周围的多余引号以及序列缩进中破折号的偏移量,那么您唯一真正的选项是使用 ruamel.yaml(免责声明:我是该包的作者):

import sys
import ruamel.yaml

yaml = ruamel.yaml.YAML()
yaml.preserve_quotes = True
yaml.indent(mapping=4, sequence=4, offset=2)

with open('input.yaml') as fp:
    data = yaml.load(fp)

test_example = data['sample']
test_example["parent2"]["childList"][0]["group"] =4
test_example["parent"]["attribute_2"] = 5
yaml.dump(data, sys.stdout)

给出:

sample:
    test_example:
    parent:
        attribute_1: 2
        attribute_2: 5
    parent2:
        childList:
          - group: 4
            type: "test"
            track_int:
              - key_1: 3
                key_2: 25
                state: present
            state: present
          - group: 4
            typr: "old"
            track_int:
              - key_1: 3
                key_2: 25
                state: present
            state: present

你的Pythontest_example的命名当然不能对应你输入文件的test_example。它被加载为 None(假设您的输入在您呈现 YAML 文档时确实缩进了)。