Search code examples
pythonyamlpyyaml

How can I print [] without string in Python in YAML file


In my yam file I am trying this

with open(fname, "w") as f:
     yaml.safe_dump({'items':['test', 'test2']}, f,
                    default_flow_style=False, width=50, indent=4)

It prints in the below format

items:
- 'test'
- 'test2'

I want the output formatted like below

items: ['test', 'test2']

How can I do that ?

EDIT:

This is my complete code

   d = {}        
   for m in ['B1', 'B2', 'B3']:
                d2 = {}
                for f in ['A1', 'A2', 'A3']:
                    # here i don't want any flow style
                    d2[f] = ['test', 'test2']
                d[m] = d2

    with open(fname, "w") as f:
        yaml.safe_dump(d, f, default_flow_style=True, width=50, indent=8)

Solution

  • Don't put the default_flow_style=False then, does the complete opposite of what you want:

    >>> import yaml
    >>> yaml.safe_dump({'items': ['test', 'test2']}, default_flow_style=False)
    'items:\n- test\n- test2\n'
    >>> yaml.safe_dump({'items': ['test', 'test2']})
    'items: [test, test2]\n'
    

    As for partial document formatting, you can do with custom representers, e.g.:

    class Items(list):
        pass
    
    
    def items_representer(dumper, data):
        return dumper.represent_sequence('tag:yaml.org,2002:seq', data, flow_style=True)
    
    
    yaml.representer.SafeRepresenter.add_representer(Items, items_representer)
    
    result = yaml.safe_dump({
        'items': Items(['test', 'test2']),
        'other list': ['1', '2'],
    }, default_flow_style=False)
    
    # items: [test, test2]
    # other list:
    # - '1'
    # - '2'
    print(result)