
Basic Key-Value Pairs
YAML primarily uses key-value pairs to represent data. Each key is followed by a colon and a space, and then its corresponding value. For example, consider the following simple YAML structure:Representing Arrays
To represent arrays (or lists) in YAML, define a key with a colon. On the next line, list each item with a dash. Below is an example that combines both key-value pairs and arrays:Grouping Properties with Dictionaries
Dictionaries (or maps) allow you to group related properties under a single key. For instance, to represent nutritional information, you might structure your YAML file with dictionaries and arrays as shown below:
Ensure you maintain consistent indentation. Extra spaces or incorrect indentation can lead to YAML syntax errors, such as accidentally nesting properties under the wrong key.
Lists of Dictionaries
YAML also supports lists that contain dictionaries. In the example below, each element in the list is a dictionary that represents the nutritional information of a fruit:When to Use Dictionaries versus Lists
A common question is when to choose a dictionary over a list. YAML, much like XML and JSON, can describe various types of data—from organizational employee records to detailed information about vehicles. For example, consider a car object with properties such as color, model, transmission, and price. A dictionary is perfect to represent a single car:
Key Differences: Dictionaries vs. Lists
It’s important to understand the fundamental differences between dictionaries and lists:-
Dictionaries:
Dictionaries are unordered collections of key-value pairs. The order of keys does not matter; what is important is the integrity of the key-value mapping. For example, the following representations of a banana are equivalent: -
Lists:
Lists are ordered collections. The sequence in which items appear is significant. For example:Changing the order of items in the list will alter the sequence, which might be important depending on your use case.