Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python yaml safe_load: How to keep the original order

Tags:

python

yaml

I am using yaml.safe_load method to process a file, and I can see that the data that is being returned by that call is in a different order

This is my code:

    a=yam.safe_load('{"method1": "value1","method2": "value2"}' )
    print(a)

And this is the output

{'method2': 'value2', 'method1': 'value1'}

What can I do to keep the original order?

like image 836
Javi DR Avatar asked Aug 04 '26 00:08

Javi DR


1 Answers

The safe_load method has been deprecated. Make sure to instantiate your YAML instance with default parameters:

from ruamel.yaml import YAML

data = yaml.load('{"method1": "value1","method2": "value2"}')
for key in data:
    print(key)

According to the YAML specification the order of keys in mappings is not to be preserved. That is not useful for YAML documents in files saved to revision control. The above represents the mapping in an ordereddict subclass for Python 2 and 3, and automatically preserves the order (as well as comments, tags etc).

like image 106
Anthon Avatar answered Aug 05 '26 12:08

Anthon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!