I want to load a YAML file into Python as an OrderedDict
. I am using yamlordereddictloader
to preserve ordering.
However, I notice that the aliased object is placed "too soon" in the OrderedDict in the output.
How can I preserve the order of this mapping when read into Python, ideally as an OrderedDict
? Is it possible to achieve this result without writing some custom parsing?
Notes:
- I'm not particularly concerned with the method used, as long as the end result is the same.
- Using sequences instead of mappings is problematic because they can result in nested output, and I can't simply flatten everything (some nestedness is appropriate).
- When I try to just use
!!omap
, I cannot seem to merge the aliased mapping (d1.dt
) into thed2
mapping. - I'm in Python 3.6, if I don't use this loader or
!!omap
order is not preserved (apparently contrary to the top 'Update' here: https://stackoverflow.com/a/21912744/2343633)
import yaml
import yamlordereddictloader
yaml_file = """
d1:
id:
nm1: val1
dt: &dt
nm2: val2
nm3: val3
d2: # expect nm4, nm2, nm3
nm4: val4
<<: *dt
"""
out = yaml.load(yaml_file, Loader=yamlordereddictloader.Loader)
keys = [x for x in out['d2']]
print(keys) # ['nm2', 'nm3', 'nm4']
assert keys==['nm4', 'nm2', 'nm3'], "order from YAML file is not preserved, aliased keys placed too early"