简体   繁体   English

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

[英]python: how to add a new key and a value in yaml file

I have the following YAML file. 我有以下YAML文件。 I need to update the YAML file with a new key-value pair using python. 我需要使用python使用新的键值对更新YAML文件。

I am doing the following but, it gives me error: 我正在做以下但是,它给了我错误:

pod = mylib.load_yaml("net/pod.yaml")
pod['spec']['nodeSelector']['key']='val'

it gives error saying KeyError:'nodeSelector' 它给错误说KeyError:'nodeSelector'

spec:
  containers:
  - image: ceridwen/networking:v1
    imagePullPolicy: Always
    name: networking
    readinessProbe:
      tcpSocket:
        port: 5000
      initialDelaySeconds: 5
      periodSeconds: 1
    restartPolicy: Always

I need to update it with a new key value 我需要用新的键值更新它

spec:
  containers:
  - image: ceridwen/networking:v1
    imagePullPolicy: Always
    name: networking
    readinessProbe:
      tcpSocket:
        port: 5000
      initialDelaySeconds: 5
      periodSeconds: 1
    restartPolicy: Always
  nodeSelector:
    key: value 

Once you load that YAML file, your pod is a dict with a single key spec . 加载YAML文件后,您的pod就是一个带有单个密钥spec的dict。 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'] : 您可以检查该键的值( print(pod['spec'] ),你会看到它是dict,只有一个密钥containers 。由于你想要为该dict添加一个额外的关键nodeSelector ,你应该添加到pod['spec']

pod['spec']['nodeSelector'] = dict(key='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. 请注意key:value输出中的key:value (在没有空格之后:keyvalue周围没有引号),不是映射而是单个标量字符串。


The "solution" given by @zwer in his comment: @zwer在评论中给出的“解决方案”:

pod["spec"] = {"nodeSelector": {"key": "val"}} is incorrect, as it will dump as: pod["spec"] = {"nodeSelector": {"key": "val"}}不正确,因为它将转储为:

spec:
  nodeSelector:
    key: val

ie replacing the value for spec and thereby deleting the existing dict/mapping with the key containers . 即替换spec的值,从而删除现有的dict /映射与密钥containers

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM