我试图从Python字典创建YAML。到目前为止,我都试过PyYAML和ruamel.yaml并且都具有相同的结果:如果输入字典中不包含列表,输出的格式不正确。
这里的脚本:
from ruamel import yaml
import sys
yaml.dump({'name': 'Enterprise', 'class': 'Galaxy', 'armament': ['photon torpedoes','phasers'], 'number': 1701}, sys.stdout)
print('\n')
yaml.dump({'name': 'Enterprise', 'class': 'Galaxy', 'number': 1701}, sys.stdout)
而这里的输出:
armament: [photon torpedoes, phasers]
class: Galaxy
name: Enterprise
number: 1701
{class: Galaxy, name: Enterprise, number: 1701}
所期望的输出是第二YAML转储应该像第一被格式化。这里发生了什么?
您正在使用旧风格的API和默认输出流风格的任何叶节点。在您的情况下,两个列表/ sequece [photon torpedoes, phasers]
和您的秒转储(其中根级别是叶节点)。
假设你不只是要解释为什么出现这种情况,又是如何改变这种行为,用新的API,使用ruamel.yaml.YAML
的情况下,默认的就是让一切流动式的,包括所有的叶节点:
from ruamel.yaml import YAML
import sys
yaml = YAML()
yaml.dump({'name': 'Enterprise', 'class': 'Galaxy', 'armament': ['photon torpedoes','phasers'], 'number': 1701}, sys.stdout)
print()
yaml.dump({'name': 'Enterprise', 'class': 'Galaxy', 'number': 1701}, sys.stdout)
赠送:
name: Enterprise
class: Galaxy
armament:
- photon torpedoes
- phasers
number: 1701
name: Enterprise
class: Galaxy
number: 1701
不过不是你想要的:-)
您现在有两个选择,让您指定什么:对你的第二个你的第一个转储和叶节点块式的叶节点流式。
第一种方法是有一个实例用于第一转储和用于第二转储“正常”之一default_flow_style
组:
from ruamel.yaml import YAML
import sys
yaml = YAML()
yaml.default_flow_style = None
yaml.dump({'name': 'Enterprise', 'class': 'Galaxy', 'armament': ['photon torpedoes','phasers'], 'number': 1701}, sys.stdout)
print()
yaml = YAML()
yaml.dump({'name': 'Enterprise', 'class': 'Galaxy', 'number': 1701}, sys.stdout)
这使:
name: Enterprise
class: Galaxy
armament: [photon torpedoes, phasers]
number: 1701
name: Enterprise
class: Galaxy
number: 1701
第二个选择是明确设置流动式要作为序列输出的对象。为此,你必须创建一个ruamel.yaml.comments.CommentedSeq
实例,装载保存流/块样式,评论等时,一般用于:
from ruamel.yaml import YAML, comments
import sys
yaml = YAML()
armaments = comments.CommentedSeq(['photon torpedoes','phasers'])
armaments.fa.set_flow_style()
yaml.dump({'name': 'Enterprise', 'class': 'Galaxy', 'armament': armaments, 'number': 1701}, sys.stdout)
print()
yaml.dump({'name': 'Enterprise', 'class': 'Galaxy', 'number': 1701}, sys.stdout)
这也给了:
name: Enterprise
class: Galaxy
armament: [photon torpedoes, phasers]
number: 1701
name: Enterprise
class: Galaxy
number: 1701
当然,这第二个选项为您提供了很好的控制(也有CommentedMap
),你可以在你的数据的所有级别有那些对象,不只是在那些藏品的叶子。
请注意,您不必加载从具有格式为你想成为一个YAML文件所需的输出时要经过这些滑稽。在这种情况下,字典RESP。名单像实例与正确的流/块式的创建,所以输出不会意外更改时,只是改变/增加值和倾倒回来。
这在documentation陈述如何使一致的输出:
yaml.dump({'name': 'Enterprise', 'class': 'Galaxy', 'number': 1701},
sys.stdout,
default_flow_style=False) # <- the important parameter
class: Galaxy
name: Enterprise
number: 1701