python:如何在yaml文件中添加新键和值 [英] python: how to add a new key and a value in yaml file
问题描述
我有以下 YAML 文件.我需要使用 python 使用新的键值对更新 YAML 文件.
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'
它给出错误说 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
推荐答案
一旦你加载了那个 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
.
这篇关于python:如何在yaml文件中添加新键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!