Skip to main content
Many people learning YAML ask: when should I use a dictionary (mapping) versus a list (sequence), and how do I combine them? This article clarifies those choices and shows how to represent nested data and multiple objects in YAML. All common data representation formats — XML, JSON, YAML — are used to describe structured information such as:
  • an organization and its employees,
  • a school and its students and grades,
  • a manufacturer and its products and specifications.
For clarity, we’ll use a car example throughout.

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:
Notes:
  • Model is a nested mapping containing Name and Year. 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:
A sequence is an ordered collection. The order of items matters.

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:
This pattern — a sequence of mappings — is the standard way to represent multiple objects of the same type, each with its own properties.

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).
This will reinforce when to choose mappings vs sequences and how to nest them effectively.

Watch Video

Practice Lab