2

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?

Anthon
  • 69,918
  • 32
  • 186
  • 246
Javi DR
  • 31
  • 2
  • Python (<3.6) dictionary does not preserve order. – falsetru May 15 '17 at 15:04
  • 3
    Possible duplicate of [In Python, how can you load YAML mappings as OrderedDicts?](http://stackoverflow.com/questions/5121931/in-python-how-can-you-load-yaml-mappings-as-ordereddicts) – Azat Ibrakov May 15 '17 at 15:14

1 Answers1

2

You should use round_trip_load instead of safe_load:

from ruamel import yaml

data = yaml.round_trip_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, so this is what the backwards compatible safe_load does. Only the round_trip_load represents the mapping in an ordereddict subclass automatically to preserve the order (and comments etc).

Anthon
  • 69,918
  • 32
  • 186
  • 246