Iterating through YAML list in python

15,073

Solution 1

If your YAML file contains:

b: 2
a: 1

Then parsing like this:

from ruamel.yaml import YAML

yaml = YAML()
input_file = 'input.yaml'

for key, value in yaml.load(open(input_file)).items():
    print(str(key))

will print b first. If you however use the (faster):

yaml = YAML(typ='safe')

this is not guaranteed, as the order of mapping keys is not guaranteed by by the YAML specification.

If you are using YAML 1.1 and PyYAML, there is no such guarantee of order, but then you should not be using yaml.load() in the first place, because it is unsafe.

Solution 2

yaml.load in this case just returns a dict, which by default is unordered. If you care about preserving order, you'd need to use an OrderedDict, see here for an example of how to do that.

Share:
15,073
Rikg09
Author by

Rikg09

Updated on June 04, 2022

Comments

  • Rikg09
    Rikg09 almost 2 years

    I'm trying to read a YAML file and print out the list I have on there in order of what it is in the file.

    So YAML:

    b: ...
    a: ...
    

    And my python is:

    for key, value in yaml.load(open(input_file)).items():
        print(str(key))
    

    The output becomes:

    a
    b
    

    However I need it to be b then a. I've also tried iteritems(), and I get the same result.

    • Anthon
      Anthon over 6 years
      Why do you do print(str(key)), does that give a different result from print(key)?
  • Rikg09
    Rikg09 over 6 years
    Thanks, that makes sense. I'll need to take a closer look at YAML in general to figure this out bette, but thanks for pointing me in the right direction :)