我使用 PyYAML 将 python 字典输出为 YAML 格式:
import yaml
d = { 'bar': { 'foo': 'hello', 'supercalifragilisticexpialidocious': 'world' } }
print yaml.dump(d, default_flow_style=False)
输出是:
bar:
foo: hello
supercalifragilisticexpialidocious: world
但我想:
bar:
foo : hello
supercalifragilisticexpialidocious : world
这个问题是否有简单的解决方案,即使是次优的解决方案?
最佳答案
好的,这是我到目前为止的想法。
我的解决方案包括两个步骤。第一步定义一个字典表示器,用于向键添加尾随空格。通过这一步,我在输出中获得了带引号的键。这就是为什么我添加第二个步骤来删除所有这些引号:
import yaml
d = {'bar': {'foo': 'hello', 'supercalifragilisticexpialidocious': 'world'}}
# FIRST STEP:
# Define a PyYAML dict representer for adding trailing spaces to keys
def dict_representer(dumper, data):
keyWidth = max(len(k) for k in data)
aligned = {k+' '*(keyWidth-len(k)):v for k,v in data.items()}
return dumper.represent_mapping('tag:yaml.org,2002:map', aligned)
yaml.add_representer(dict, dict_representer)
# SECOND STEP:
# Remove quotes in the rendered string
print(yaml.dump(d, default_flow_style=False).replace('\'', ''))
关于python - PyYAML,如何对齐 map 条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13293680/