Maps are data structures used to store key-value pairs. There are two ways to represent maps in YAML:
Mapping nodes are used to represent complex data structures, such as hashes or dictionaries. In a mapping node, each key must be unique and each key can have only one value. The order of the keys is not important.
Mapping scalars are used to represent simple data structures, such as arrays or tuples. In a mapping scalar, each key must be unique but each key can have multiple values. The order of the keys is important.
map:- key1: value1- key2: value2- key3: value3
In YAML, maps are represented using the colon (:
) character. We can also use quotation marks ("
or '
) to enclose the keys and values if we need to.
foo: barbaz: qux
We can also nest maps within maps:
foo:nested_map:key: value
As we can see, the indentation is important in YAML. The nested map must be indented further than the parent map.
The following code snippet shows how to represent employee data using maps in YAML:
---name: John Smithage: 25address:street: 123 Main Streetcity: New Yorkstate: NYzip: 10001...
In the example above, the first key is name
and the value is John Smith
. The second key is age
and the value is 25
. The third key is address
and the value is a nested map with four keys and four values. The fourth key is zip
and the value is 10001
.
In Python, a YAML map is a dictionary. It's a collection of key-value pairs, where the keys are unique strings and the values can be anything.
To create a YAML map in Python, we first need to install the PyYAML module. Once we have PyYAML installed, we can create a YAML map:
import yamlfrom yaml import BaseLoadermy_map = yaml.load("""key1: value1key2: value2key3: value3""", BaseLoader)print(my_map)print(my_map['key1']) # Outputs value1print(my_map['key2']) # Outputs value2print(my_map['key3']) # Outputs value3
The code above will output the following dictionary:
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
The keys in a YAML map must be unique. We can access the values in a YAML map using square brackets:
my_map['key1']
If we try to access a key that doesn't exist, we get an error.
To represent a map in YAML, we can use either mapping nodes or mapping scalars. In most cases, it is recommended to use mapping nodes. However, if we need to preserve the order of the keys, then we should use mapping scalars. We also learned how to create and parse YAML maps in Python.
Note: If you want to learn more about YAML, take the course Learn YAML from Scratch.