Search code examples
pythondictionaryyamlpyyaml

How to maintain order of insertion of keys when loading file into yaml?


I am trying to use YAML for a python script. The YAML file I have written resembles this:

1:
  name: apple
  price: 5
3:
  name: orange
  price: 6
2:
  name: pear
  price: 2

When I load the YAML file using yaml.load the dictionary is sorted by the keys so it appears in order 1,2,3. How do I maintain the order 1,3,2?


Solution

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

    gives

    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 1, 2 , 3 in python dicts.