Javi DR
Javi DR

Reputation: 51

Python yaml safe_load: How to keep the original order

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?

Upvotes: 4

Views: 2946

Answers (1)

Anthon
Anthon

Reputation: 76802

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).

Upvotes: 1

Related Questions