如何用yaml中的字典替换字符串
我有一个看起来像这样的yaml:
- k1: /etc/prometheus/auxiliaryfiles/mac-jwt-cne
k2: abcd
k3:
k4:
z1:
- asfa
k5: zxcv
key_001:
__TARGETS__
我有一个词典,看起来像:
{'a':[12,23,34]}
想在yaml中用上面的字典替换__ targets __
key_001:
- a:
- 12
- 23
- 34
yaml_dict = readYaml("lib/above_Yaml.yaml")
d = {'a': [12, 23, 34]}
replacements = {'__TARGETS__':[d]}
for k, v in yaml_dict.items():
if v in replacements:
yaml_dict[k] = replacements[v]
dumped = yaml.safe_dump(yaml_dict)
print(dumped)
我 以下错误:
if v in replacements:
TypeError: unhashable type: 'dict'
I have a YAML which looks like this:
- k1: /etc/prometheus/auxiliaryfiles/mac-jwt-cne
k2: abcd
k3:
k4:
z1:
- asfa
k5: zxcv
key_001:
__TARGETS__
and I have a dictionary which looks like:
{'a':[12,23,34]}
I want to replace __TARGETS__
in YAML with the dictionary above so the resultant YAML should look like:
key_001:
- a:
- 12
- 23
- 34
My Code:
yaml_dict = readYaml("lib/above_Yaml.yaml")
d = {'a': [12, 23, 34]}
replacements = {'__TARGETS__':[d]}
for k, v in yaml_dict.items():
if v in replacements:
yaml_dict[k] = replacements[v]
dumped = yaml.safe_dump(yaml_dict)
print(dumped)
I get the following error:
if v in replacements:
TypeError: unhashable type: 'dict'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我将使用递归搜索并替换的方法尝试:
out:out:
注意:这需要 pyyaml
I would try with an approach using a recursive search and replace, like this:
Out:
Note: this requires pyyaml