我使用yaml库中的safe_load在python中的变量中有这个yaml_file:
domainInfo:
AdminUserName: '--FIX ME--'
AdminPassword: '--FIX ME--'
topology:
Name: 'wld-pil-10'
ConfigBackupEnabled: true
AdminServerName: 'wls-pil-10-sa-adm-n0'
DomainVersion: 12.2.1.4.0
ProductionModeEnabled: true
ArchiveConfigurationCount: 20
Cluster:
'test-bruno-jee-r01a-c01':
ClientCertProxyEnabled: true
WeblogicPluginEnabled: true
Server:
'wls-pil-10-sa-adm-n0':
ListenPort: 11030
WeblogicPluginEnabled: true
ClientCertProxyEnabled: true
Machine: 'wlm-pil-10-n0'
'test-bruno-jee-r01a-it-c01-m1-n1':
ListenPort: 10022
WeblogicPluginEnabled: true
ClientCertProxyEnabled: true
NMSocketCreateTimeoutInMillis: 30000
Machine: 'wlm-pil-10-n1'
'test-bruno-jee-r02a-it-c01-m1-n1':
ListenPort: 10025
WeblogicPluginEnabled: true
ClientCertProxyEnabled: true
NMSocketCreateTimeoutInMillis: 30000
Machine: 'wlm-pil-10-n2'
为了拆分此yaml文件,我试图将键和值放入新词典中,但未成功。我想念什么?我知道我需要某种方式的字典,是否需要使用其他模块(例如pyyaml或ruamel)?
yaml_cluster = {}
yaml_cluster["topology"]["Name"] = yaml_file["topology"]["Name"]
yaml_cluster["topology"]["AdminServerName"] = yaml_file["topology"]["AdminServerName"]
结果:
致命的:[wls-pil-103-sa-adm-n0]:失败!=> {“已更改”:true,“ msg”:“非零返回码”,“ rc”:1,“ stderr”:“跟踪(最近一次调用):\ n文件” / tmp / ansible-tmp -1611083722.9917288-55849-215378473850896 / split_yaml.py“,第32行,位于\ n yaml_cluster [” topology“] [” Name“] = yaml_file [” topology“] [” Name“] \ nKeyError:'topology'\ n” ,“ stderr_lines”:[“追踪(最近一次通话):”,“文件” /tmp/ansible-tmp-1611083722.9917288-55849-215378473850896/split_yaml.py“,第32行,”,“ yaml_cluster [” topology“ ] [“ Name”] = yaml_file [“ topology”] [“ Name”] “,” KeyError:'topology'“ ],
您收到的错误是因为yaml_cluster["topology"]["Name"]
分配了一个不存在任何键的值。yaml_cluster["topology"]
不存在,因此您不能为该键分配任何内容Name
。
标准库中的Collections模块提供了一个类collections.defaultdict
,该类为键提供默认值(如果不存在)。在您的情况下defaultdict
,将空字典作为默认值的a将值设置yaml_cluster["topology]
为{}
(空字典),Name
然后可以像往常一样为字典分配键值。
from collections import defaultdict
yaml_cluster = defaultdict(dict) # Specifying dictionary as default value for missing keys
yaml_cluster["topology"]["Name"] = yaml_file["topology"]["Name"]
yaml_cluster["topology"]["AdminServerName"] = yaml_file["topology"]["AdminServerName"]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句