Mappings (Dictionaries) 📑¶
Mappings (also known as dictionaries or hash maps) in YAML are collections of key-value pairs. They are essential for representing structured data.
Basic Mappings¶
A basic mapping consists of key-value pairs separated by a colon and space.
yml
person:
name: chaitu-ycr
age: 30
city: chennai 🏙️
- person is a key that maps to another mapping.
- Inside the person mapping, there are keys (name, age, city) with their respective values.
Nested Mappings¶
Mappings can contain other mappings, creating a nested structure.
yml
company:
name: ycr Corp
location:
city: chennai 🏙️
state: Tamil Nadu 🛕
employees:
- name: chaitu-ycr
role: Developer 👩💻
- name: ycr dummy
role: Designer 🎨
- company is a mapping with nested mappings for location and employees.
- employees is a list of mappings, each representing an employee.
Inline Mappings¶
For simple structures, mappings can be written in a single line using curly braces {}
.
yml
address: {street: 123 Main St, city: chennai, zip: 12345}
- Inline mapping is a concise way to represent simple key-value pairs.
Complex Keys¶
YAML allows the use of complex types, such as sequences or mappings, as keys. These are enclosed in ?
and :
.
yml
? [first, second]
: "Tuple as a key"
- The key [first, second] is a sequence used as a key for the value "Tuple as a key".
Combining Mappings and Sequences¶
You can combine mappings and sequences to create complex data structures.
yml
project:
name: Build Website
tasks:
- title: Design Layout 🎨
status: Completed ✅
- title: Implement Backend 🖥️
status: In Progress 🔄
- title: Test Functionality 🧪
status: Pending ⏳
- tasks is a list of mappings, each representing a task with title and status.
Anchors and Aliases¶
Anchors (&
) and aliases (*
) allow you to reuse values within a YAML document.
yml
defaults: &defaults
country: INDIA in
currency: RUPEE 💵
location1:
<<: *defaults
city: chennai 🏙️
location2:
<<: *defaults
city: Pondicherry 🌴
- defaults is an anchor that can be reused in other mappings using
<<:
and*