Python 3.x DoubleQuotedScalarString如何应用于CommentedMap

Python 3.x DoubleQuotedScalarString如何应用于CommentedMap,python-3.x,ruamel.yaml,Python 3.x,Ruamel.yaml,当我使用ruamel.yaml库的CommentedMap存储有序词典时,我需要将CommentedMap的内容作为字符串放入词典的值中,但当我使用DoubleQuotedScalarString操作它时,输出带有不需要的字段,如ordereddict import ruamel.yaml from ruamel.yaml.comments import CommentedMap # CommentedMap用于解决ordereddict数据dump时带"!omap"

当我使用
ruamel.yaml
库的
CommentedMap
存储有序词典时,我需要将CommentedMap的内容作为字符串放入词典的值中,但当我使用
DoubleQuotedScalarString
操作它时,输出带有不需要的字段,如
ordereddict

import ruamel.yaml
from ruamel.yaml.comments import CommentedMap      # CommentedMap用于解决ordereddict数据dump时带"!omap"这样的字段
from ruamel.yaml.scalarstring import SingleQuotedScalarString,DoubleQuotedScalarString
from pathlib import Path
yaml = ruamel.yaml.YAML()
yaml.preserve_quotes = True
yaml.indent(mapping=4, sequence=6, offset=4)

file_yml = CommentedMap()
test = CommentedMap()
test['test1'] = "test1"
test['test2'] = "test2"
file_yml["test"] = DoubleQuotedScalarString(test)

path = Path("./test.yaml")
yaml.dump(file_yml, path)
结果如下

test: "ordereddict([('test1', 'test1'), ('test2', 'test2')])"
我期待的是测试的结果,“{'test1':'test1','test2':'test2'}”


如果您能告诉我如何实现它,我将不胜感激。

您不应该对
注释地图应用
DoubleQuotedScalarString
。前者唯一有用的是确保单个字符串(可能是映射或序列的一部分)获得双引号。通过将其应用于
CommentedMap
,您可以将整个内容转换为一个字符串,
CommntedMap
是一个
ordereddict

import ruamel.yaml
from ruamel.yaml.comments import CommentedMap      # CommentedMap用于解决ordereddict数据dump时带"!omap"这样的字段
from ruamel.yaml.scalarstring import SingleQuotedScalarString,DoubleQuotedScalarString
from pathlib import Path
yaml = ruamel.yaml.YAML()
yaml.preserve_quotes = True
yaml.indent(mapping=4, sequence=6, offset=4)

file_yml = CommentedMap()
test = CommentedMap()
test['test1'] = "test1"
test['test2'] = "test2"
file_yml["test"] = DoubleQuotedScalarString(test)

path = Path("./test.yaml")
yaml.dump(file_yml, path)
你或许应该做:

test = dict()
随后:

file_yml["test"] = str(test)
在Python的现代版本中,这将保留键插入顺序,并且应该添加引号,因为标量不能以
{
开头,否则会自动被引用

如果测试在作为字符串转储之前需要是一个
CommentedMap
,则将其强制转换为dict:

test = CommentedMap()
.....
file_yaml["test"] = str(dict(test))

很抱歉,由于之前的工作,
文件_yml
必须是
CommentedMap
类型,但我希望能够从上面的案例中传输它,我尝试转换
str()
,但仍然携带
订购的dict
。预计将有一种适当的方式来实现上述要求。对不起,我误读了。
文件_yaml
与此无关,
测试
应该是一份口述,或是根据口述进行转换。我更新了我的答案。