Home > Software design >  Preserving order of dictionary while using ruamel.yaml
Preserving order of dictionary while using ruamel.yaml

Time:04-15

I am using ruamel.yaml for dumping a dict to a yaml file. While doing so, I want to keep the order of the dictionary. That is how I came across the question Keep YAML file order with ruamel. But this solution is not working in my case:

  • The order is not preserved.
  • adding tags like !!python/object/apply:ruamel.yaml.comments.CommentedMap or dictitems
import ruamel.yaml
from ruamel.yaml.comments import CommentedMap as ordereddict

generated_file = os.path.join('data_TEST.yaml')
data_dict = {'Sources': {'coil': None},  'Magnet': 'ABC', 'Current': ordereddict({'heat': {'i': [[]], 'h': None, }})}
data_dict = ordereddict(data_dict)

with open(generated_file, 'w') as yaml_file:
    ruamel.yaml.dump(data_dict, yaml_file, default_flow_style=False)

The used dictionary is just an arbitrary one and in the end an automatically created array that could look different is going to be used. So, we cannot hard-code the mapping of the dictionaries in the dictionary like in my example.

Result:

!!python/object/apply:ruamel.yaml.comments.CommentedMap
dictitems:
  Current: !!python/object/apply:ruamel.yaml.comments.CommentedMap
    dictitems:
      heat:
        h: null
        i:
        - []
  Magnet: ABC
  Sources:
    coil: null

Desired result:

Sources:
    coil: null
Magnet: ABC
Current:  
    heat:
    h: null
    i:
    - []

CodePudding user response:

You should really not be using the old PyYAML API that sorts keys when dumping.

Instantiate a YAML instance and use its dump method:

 yaml = ruamel.yaml.YAML()
 yaml.dump(data, stream)
  • Related