Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dumping a dictionary to a YAML file while preserving order

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?

like image 577
Ben Avatar asked Jul 24 '15 07:07

Ben


People also ask

Does YAML preserve order?

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.

What method do you use to convert Python dictionary format into YAML?

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 .

Does YAML order matter?

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.


1 Answers

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) 
like image 163
Eric Avatar answered Nov 13 '22 15:11

Eric