Python 2.7 与ruamel yaml won的价值变化';不起作用而忽略缩进

Python 2.7 与ruamel yaml won的价值变化';不起作用而忽略缩进,python-2.7,indentation,pyyaml,ruamel.yaml,Python 2.7,Indentation,Pyyaml,Ruamel.yaml,我有一个问题,以正确的格式将数据转储回YAML。研究了其他类似的问题,但没有找到解决此问题的方法。 Python中的当前代码: template = yaml.load(open(templateFile), Loader=yaml.RoundTripLoader) template["key"] = new_value yaml.dump(template, sys.stdout, Dumper=yaml.RoundTripDumper, indent=2) 输入: parameters

我有一个问题,以正确的格式将数据转储回YAML。研究了其他类似的问题,但没有找到解决此问题的方法。 Python中的当前代码:

template = yaml.load(open(templateFile), Loader=yaml.RoundTripLoader)

template["key"] = new_value

yaml.dump(template, sys.stdout, Dumper=yaml.RoundTripDumper, indent=2)
输入:

parameters:
  key: value
输出:

parameters:
  key: value
key: new_value
预期产出:

parameters:
  key: new_value

应如何修改代码,以更改旧的“键”值,或输入具有正确缩进的新值?

您必须将
新值
分配给正确的映射/dict:

import sys
from ruamel import yaml

template_file = 'input.yaml'
new_value = 'new_value'

template = yaml.load(open(template_file), Loader=yaml.RoundTripLoader)
template['parameters']['key'] = new_value
yaml.dump(template, sys.stdout, Dumper=yaml.RoundTripDumper, indent=2)
在“
键下”缩进的新值需要:

template['parameters']['newkey'] = 'added_value'

请注意,对于Python变量,如
template\u file
RoundTripLoader
/
RoundTripLoader
是类的名称)

您必须将
新值
分配给正确的映射/dict:

import sys
from ruamel import yaml

template_file = 'input.yaml'
new_value = 'new_value'

template = yaml.load(open(template_file), Loader=yaml.RoundTripLoader)
template['parameters']['key'] = new_value
yaml.dump(template, sys.stdout, Dumper=yaml.RoundTripDumper, indent=2)
在“
键下”缩进的新值需要:

template['parameters']['newkey'] = 'added_value'

请注意,对于Python变量,如
template\u file
RoundTripLoader
/
RoundTripLoader
是类的名称)通常使用snake\u case)

“查看其他类似问题”包括链接和说明,请说明原因。“查看其他类似问题”包括链接和解释为什么不请。