WojtylaCz
WojtylaCz

Reputation: 368

PyYAML - is order of a list preserved?

With following YAML file at filepath containing list:

nodes:
    - first
    - second
    - third

When read this file with pyyaml,

config = yaml.load(file(filepath, 'r'))

is the order of the list always preserved?
In other words, is it guaranteed that it will always true that config['nodes'][0] is 'first' ?

Upvotes: 4

Views: 6216

Answers (1)

Anthon
Anthon

Reputation: 76802

Yes, the order of sequences is preserved. In YAML a sequence (which maps to a python list):

Represents a collection indexed by sequential integers starting with zero. Example bindings to native types include Perl’s array, Python’s list or tuple, and Java’s array or Vector.

What is not preserved in YAML normally is the order of keys in mappings (although there is of course an order in any serialised form of such a mapping), and such mappings are normally read in as python dicts, which have no ordering in their keys either.

Upvotes: 5

Related Questions