I am trying to use YAML for a python script. The YAML file I have written resembles this:
In the YAML specification it is explicitly stated that mapping keys have no order. In a file however they have. If you want a simple way to solve this replace PyYAML with ruamel.yaml (disclaimer: I am the author of that package, which is a superset of PyYAML) and use
round_trip_load(), it will give you ordered dictionaries without the hassle of using single mapping item sequence elements that you need for specifying ordered dicts the "official" way.
import ruamel.yaml yaml_str = """\ 1: name: apple price: 5 3: name: orange price: 6 2: name: pear price: 2 """ data = ruamel.yaml.round_trip_load(yaml_str) for key in data: print(key)
1 3 2
BTW PyYAML doesn't sort by the keys, that ordering is just a side-effect of calculating hashes and inserting integer keys
3 in python