我正在执行以下 python 代码:
import yaml
foo = {
'name': 'foo',
'my_list': [{'foo': 'test', 'bar': 'test2'}, {'foo': 'test3', 'bar': 'test4'}],
'hello': 'world'
}
print(yaml.dump(foo, default_flow_style=False))
但正在打印:
hello: world
my_list:
- bar: test2
foo: test
- bar: test4
foo: test3
name: foo
代替:
hello: world
my_list:
- bar: test2
foo: test
- bar: test4
foo: test3
name: foo
我怎样才能缩进my_list
元素就这样?
这张票 https://web.archive.org/web/20170903201521/https://pyyaml.org/ticket/64建议当前的实现正确遵循the spec http://yaml.org/spec/1.2/spec.html#id2777534:
这 ”-”, ”?”用于表示块集合条目的“:”字符被人们认为是缩进的一部分。这是由相关制作部门根据具体情况进行处理。
在同一个线程上,还有这段代码片段 https://web.archive.org/web/20170903201521/https://pyyaml.org/ticket/64#comment:5(修改以适合您的示例)以获得您正在寻找的行为:
import yaml
class MyDumper(yaml.Dumper):
def increase_indent(self, flow=False, indentless=False):
return super(MyDumper, self).increase_indent(flow, False)
foo = {
'name': 'foo',
'my_list': [
{'foo': 'test', 'bar': 'test2'},
{'foo': 'test3', 'bar': 'test4'}],
'hello': 'world',
}
print yaml.dump(foo, Dumper=MyDumper, default_flow_style=False)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)