How to represent dictionaries in YAML

What are dictionaries?

Dictionaries are a common data structure in many programming languages. A dictionary is a data structure that allows us to store data in key-value pairs.

In YAML, dictionaries are represented as mappings. A mapping is a collection of key-value pairs, where each key is mapped to a value.

For example, the following is a graphical representation of a dictionary that maps several countries to their capital cities.

%0 node_1653834761882 Luanda node_1653834799037 Angola node_1653834761882->node_1653834799037 node_1653834725699 Andorra node_1653834684065 Andorra la Vella node_1653834725699->node_1653834684065 node_2 Algeria node_1653834647347 Algiers node_2->node_1653834647347 node_1 Albania node_1_2 Tirana node_1->node_1_2 node_0 Afghanistan node_0_1 Kabul node_0->node_0_1
A dictionary that maps countries to their capital cities

In the example above, the countries mapping contains five key-value pairs. The keys are on the left, and the values are on the right. The keys are "Afghanistan", "Albania", "Algeria", "Andorra", and "Angola," and their corresponding values are "Kabul", "Tirana", "Algiers", "Andorra la Vella", and "Luanda," respectively.

When we want to represent a dictionary in YAML, we can use either block-style or flow-style notation.

Representing dictionaries in block-style

The following is YAML code for the above mapping represented in block-style notation:

---
countries:
Afghanistan: Kabul
Albania: Tirana
Algeria: Algiers
Andorra: Andorra la Vella
"Angola": "Luanda"

As we can see, in block-style notation each key is separated from its value by a colon (:) followed by a space. We can use also quotation marks around the key or value strings, as in line 7 above.

Representing dictionaries in flow-style

We can also represent mappings in flow-style notation. The following is an equivalent YAML code to represent the mapping above in flow-style notation:

countries: {Afghanistan: Kabul, Albania: Tirana, Algeria: Algiers, Andorra: Andorra la Vella, "Angola": "Luanda"}

In flow-style notation, all of the key-value pairs are represented on a single line. As we can see, the dictionary is represented as a sequence of key-value pairs. We use the mapping start token ({) and the mapping end token (}) to map the key-value pairs in flow-style representation. These are used to indicate the beginning and the end of a mapping, respectively.

Each key is separated from its value by a colon (:) followed by a space. The key-value pairs are separated by commas (,).

Flow-style notation is more compact than block-style notation. However, it can be more difficult to read. Therefore, it is generally advisable to use the block-style notation for mappings that contain more than a few key-value pairs.

Unlock your potential: YAML basics series, all in one place!

To continue your exploration of YAML basics, check out our series of Answers below:

Free Resources