python yaml.dump 缩进错误

标签 python yaml indentation

我正在执行以下 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 元素?

最佳答案

This ticket建议当前的实现正确地遵循 the spec :

The “-”, “?” and “:” characters used to denote block collection entries are perceived by people to be part of the indentation. This is handled on a case-by-case basis by the relevant productions.

在同一个线程上,还有this code snippet (修改以适合您的示例)以获得您正在寻找的行为:

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)

关于python yaml.dump 缩进错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25108581/

相关文章:

python - 从 CSV 初始化字符串生成器

Python - 从域名和页面标题解析公司名称

python - 值错误 : I/O operation on closed file to_excel pandas

python - 创建端口转发代理以加速网络

Ruby:将转义字符串写入 YAML

java - 在 Eclipse 中为 Java try-with-resources 设置括号之间的缩进

html - 为什么使用显示 :hidden for text in HTML? 被认为是不好的做法

ruby-on-rails-3 - Yaml 输出填充了 !map:ActiveSupport::HashWithIndifferentAccess

Python 记录器未选择配置时间格式。

Emacs:将任何 "//"模式移动到特定列