- an organization and its employees,
- a school and its students and grades,
- a manufacturer and its products and specifications.
Single object: use a mapping (dictionary)
A car is a single object with named properties: color, model, transmission, price. To represent one object and its attributes, use a YAML mapping:Modelis a nested mapping containingNameandYear. Use nested mappings when a property itself has sub-properties.- Keys in mappings are names (strings) that map to scalars or other collections (mappings or sequences).
Multiple values of the same kind: use a sequence (list)
When you need several values of the same type (for example, a list of car names), use a YAML sequence:Multiple objects: use a sequence of mappings
To store a collection of cars where each entry has full properties, use a sequence of mappings. Each list item is a mapping that describes one car:Quick rules of thumb
- Use a mapping (dictionary) to represent a single object with named properties.
- Use a sequence (list) to represent multiple values/items of the same kind.
- Use a sequence of mappings when you need to represent several objects and each object has its own set of properties.
Ordering and comments
- Mappings (dictionaries) are unordered by the YAML specification. Your program should not rely on key order for correctness. Some YAML parsers preserve insertion order, but it’s an implementation detail, not guaranteed by the spec.
- Sequences (lists) are ordered. Different item order means different meaning:
- Comments start with
#when used outside quoted scalars; anything after#on that line is ignored by the parser:
Remember: mappings are unordered by specification (key order doesn’t affect meaning), sequences are ordered (item order matters), and
# begins a comment when used outside a quoted string.Next steps
Try converting datasets between:- a single mapping (one object),
- a sequence of scalars (list of names),
- and a sequence of mappings (list of full objects).
Links and references
- YAML specification: https://yaml.org/spec/
- YAML tutorial and examples: https://yaml.org/start.html
- Related: JSON vs YAML overview