【问题标题】:How to read the yaml file as dictionary and update value using python如何将yaml文件读取为字典并使用python更新值
【发布时间】:2018-04-17 07:07:27
【问题描述】:

我需要编写函数来读取 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

我该怎么做?

【问题讨论】:

  • 这个 YAML 文件/文档不是字典,它是映射和序列(和标量)的组合。在根目录有一个映射,它作为 Python 字典加载,但是说“YAML 文件是 [a] 字典”是不正确的。

标签: python yaml file-handling pyyaml


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2016-09-26
    • 2015-04-17
    • 2022-10-05
    • 1970-01-01
    • 2021-10-07
    • 2013-07-20
    • 2018-06-22
    • 2012-12-16
    • 1970-01-01
    相关资源
    最近更新 更多