且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

python:如何在yaml文件中添加新键和值

更新时间:2023-11-30 13:20:16

一旦你加载了那个 YAML 文件,你的 pod 就是一个带有单键 spec 的字典.您可以检查该键的值 (print(pod['spec']),您将看到这是 dict,只有一个键 containers.由于您想要添加一个额外的键 nodeSelector 到那个 dict 你应该添加到 pod['spec']:

Once you load that YAML file, your pod is a dict with a single key spec. You can check the value for that key (print(pod['spec']) and you'll see that that is dict, with a single key containers. Since you want add an extra key nodeSelector to that dict you should add to pod['spec']:

pod['spec']['nodeSelector'] = dict(key='value')

请注意输出中的 key:value(: 后没有空格,key 后没有引号)code>value),不是映射而是单个标量字符串.

Please note that the key:value you had in your output (without a space after the : and without quotes around key and value), is not a mapping but a single scalar string.

@zwer 在评论中给出的解决方案":

The "solution" given by @zwer in his comment:

pod["spec"] = {"nodeSelector": {"key": "val"}}不正确,因为它会转储为:

pod["spec"] = {"nodeSelector": {"key": "val"}} is incorrect, as it will dump as:

spec:
  nodeSelector:
    key: val

即替换 spec 的值,从而使用键 containers 删除现有的字典/映射.

i.e. replacing the value for spec and thereby deleting the existing dict/mapping with the key containers.