0

I'd like to write the following output to a YAML file:

'0':[]
'1':[]
'2':[]
'3':[]
...
'100':[]

I can do this:

import yaml
d = {str(i):[] for i in range(101)}
with open('result.yml', 'w') as yaml_file:
    yaml.dump(d, yaml_file, default_flow_style=False)

But the order won't be preserved. How can I get that desired output?

Thanks!

anon_swe
  • 8,791
  • 24
  • 85
  • 145

1 Answers1

0

YAML defines that the order of mapping keys must not convey content information. Therefore, you must not depend on the order of mapping keys when you're using YAML. See also this discussion. If what you're doing depends on the order of keys, you should use a list, e.g.:

import yaml

d = [{str(i): []} for i in range(101)]
with open('result.yml', 'w') as yaml_file:
    yaml.dump(d, yaml_file, default_flow_style=False)

Which gives you:

- '0': []
- '1': []
- '2': []

With the order of keys preserved because you wrapped the key-value pairs in a list.

If you really need to write the mapping as it is with the order you want it to have, you can still use the low-level event API:

import yaml
from yaml.events import *

d = [StreamStartEvent(), DocumentStartEvent(),
     MappingStartEvent(anchor=None, tag=u'tag:yaml.org,2002:map', implicit=True)]
for i in range(101):
  d.extend([ScalarEvent(anchor=None, tag=u'tag:yaml.org,2002:str', value=str(i),
                       implicit=(True, True)),
            SequenceStartEvent(anchor=None, tag=u'tag:yaml.org,2002:seq', implicit=True),
            SequenceEndEvent()])
d.extend([MappingEndEvent(), DocumentEndEvent(), StreamEndEvent()])

with open('result.yml', 'w') as yaml_file:
  yaml.emit(d, yaml_file)
flyx
  • 35,506
  • 7
  • 89
  • 126