Search code examples
pythonpython-3.xyamlpyyaml

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


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 

Solution

  • 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.