PyYAML, how to align map records?

I use PyYAML to output the Python dictionary to YAML format:

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

Output:

 bar: foo: hello supercalifragilisticexpialidocious: world 

But I would like to:

 bar: foo : hello supercalifragilisticexpialidocious : world 

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

+5
source share
1 answer

Well, that’s what I’ve come up with so far.

My decision involves two steps. The first step is to define a dictionary for adding trailing spaces to keys. At this point, I get the keys in quotation marks in the output. This is why I am adding a second step to remove all of 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('\'', '')) 
+5
source

Source: https://habr.com/ru/post/1444865/


All Articles