I've been trying to dump a dictionary to a YAML file. The problem is that the program that imports the YAML file needs the keywords in a specific order. This order is not alphabetically.
import yaml import os baseFile = 'myfile.dat' lyml = [{'BaseFile': baseFile}] lyml.append({'Environment':{'WaterDepth':0.,'WaveDirection':0.,'WaveGamma':0.,'WaveAlpha':0.}}) CaseName = 'OrderedDict.yml' CaseDir = r'C:\Users\BTO\Documents\Projects\Mooring code testen' CaseFile = os.path.join(CaseDir, CaseName) with open(CaseFile, 'w') as f: yaml.dump(lyml, f, default_flow_style=False)
This produces a *.yml file which is formatted like this:
- BaseFile: myfile.dat - Environment: WaterDepth: 0.0 WaveAlpha: 0.0 WaveDirection: 0.0 WaveGamma: 0.0
But what I want is that the order is preserved:
- BaseFile: myfile.dat - Environment: WaterDepth: 0.0 WaveDirection: 0.0 WaveGamma: 0.0 WaveAlpha: 0.0
Is this possible?
What is not preserved in YAML normally is the order of keys in mappings (although there is of course an order in any serialised form of such a mapping), and such mappings are normally read in as python dicts, which have no ordering in their keys either.
Using dump(), we can translate Python objects into YAML format and write them into YAML files to make them persistent and for future use. This process is known as YAML Serialization. The yaml. dump() method accepts two arguments, data and stream .
In general the order of keys in a YAML file does not matter. Neither do blank lines. Indentation may be with any number of spaces, as long as it is consistent throughout the file.
yaml.dump
has a sort_keys
keyword argument that is set to True
by default. Set it to False
to not reorder:
with open(CaseFile, 'w') as f: yaml.dump(lyml, f, default_flow_style=False, sort_keys=False)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With