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

不问归期 提交于 2020-01-14 10:28:29

问题


I have the following YAML file. I need to update the YAML file with a new key-value pair using python.

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'

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 

回答1:


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')

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.


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

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

spec:
  nodeSelector:
    key: val

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



来源:https://stackoverflow.com/questions/50030819/python-how-to-add-a-new-key-and-a-value-in-yaml-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!