Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyYAML, how to align map entries?

I use PyYAML to output a python dictionary to YAML format:

import yaml
d = { 'bar': { 'foo': 'hello', 'supercalifragilisticexpialidocious': 'world' } }
print yaml.dump(d, default_flow_style=False)

The output is:

bar:
  foo: hello
  supercalifragilisticexpialidocious: world

But I would like:

bar:
  foo                                : hello
  supercalifragilisticexpialidocious : world

Is there a simple solution to that problem, even a suboptimal one?

like image 747
mouviciel Avatar asked Nov 08 '12 16:11

mouviciel


1 Answers

Ok, here is what I've come up with so far.

My solution involves two steps. The first step defines a dictionary representer for adding trailing spaces to keys. With this step, I obtain quoted keys in the output. This is why I add a second step for removing all these quotes:

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('\'', ''))
like image 87
mouviciel Avatar answered Oct 12 '22 23:10

mouviciel