0

I am using yaml module to generate yaml file, But actually I am not getting proper expected output and below is the code:

import yaml
list1 = [{'Test01': '01', 'Test02': '02'}, {'Test03': '03', 'Test04': '04'}]
some_data = {"data": list1} 
yaml_data = {
  'version': '1.0'
}
yaml_data.update(some_data)

print(yaml.dump(yaml_data, default_flow_style=False))

Actual Output:

data:
- Test01: '01'
  Test02: '02'
- Test03: '03'
  Test04: '04'
version: '1.0'

Expected output:

data:
  - 
    Test01: '01'
    Test02: '02'
  - 
    Test03: '03'
    Test04: '04'
version: '1.0'
Palla veera
  • 113
  • 3
  • 7
  • That is not the actual output from that program. PyYAML uses stream based processing, with a much abused helper if you don't provide a stream, for when you need a string for further processing. Doing `print(yaml.dump(d))` is inefficient in speed and memory usage: use `yaml.dump(d, sys.stdout)` instead. As far as I remember, there is nothing in the PyYAML documentation that warrants your expectation. – Anthon Feb 25 '19 at 16:00

1 Answers1

0

You can use OrderedDict instead of dict to preserve the order in yaml.dump()

from collections import OrderedDict

import yaml

list1 = [{'Test01': '01', 'Test02': '02'}, {'Test03': '03', 'Test04': '04'}]
some_data = OrderedDict({"data": list1})
yaml_data = OrderedDict({
  'version': '1.0'
})
yaml_data.update(some_data)
print(yaml_data)


def represent_dictionary_order(self, dict_data):
    return self.represent_mapping('tag:yaml.org,2002:map', dict_data.items())


def setup_yaml():
    yaml.add_representer(OrderedDict, represent_dictionary_order)


setup_yaml()
print(yaml.dump(yaml_data, default_flow_style=False))
Logovskii Dmitrii
  • 2,629
  • 4
  • 27
  • 44