简体   繁体   中英

Preserving order of dictionary while using ruamel.yaml

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:
    - []

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM