Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

YAML Lists and Dictionaries Tutorial

Introduction to YAML

YAML (YAML Ain't Markup Language) is a human-readable data serialization standard that can be used in conjunction with all programming languages. It is commonly used for configuration files and in applications where data is being stored or transmitted.

YAML Basics

Before diving into lists and dictionaries, let's cover some basic syntax rules of YAML:

  • YAML uses indentation to denote structure. Indentation is achieved using spaces (not tabs).
  • YAML files use the .yaml or .yml extension.
  • Comments in YAML start with a #.

YAML Lists

Lists in YAML are simple collections of items. Each item in a list is prefixed with a hyphen (-).

- item1
- item2
- item3
                

To create a list of dictionaries, each dictionary is an item in the list:

- name: John Doe
  age: 30
- name: Jane Doe
  age: 25
                

YAML Dictionaries

Dictionaries (or mappings) in YAML are collections of key-value pairs. Each key-value pair is separated by a colon (:).

name: John Doe
age: 30
address:
  street: 123 Main St
  city: Anytown
                

Dictionaries can also contain lists:

name: John Doe
age: 30
children:
  - name: Jimmy Doe
    age: 5
  - name: Jenny Doe
    age: 3
                

Complex Structures

YAML allows for complex nested structures. Here is an example combining lists and dictionaries:

users:
  - name: John Doe
    age: 30
    contacts:
      email: john.doe@example.com
      phone: 123-456-7890
  - name: Jane Doe
    age: 25
    contacts:
      email: jane.doe@example.com
      phone: 098-765-4321
                

YAML in Ansible

Ansible, a popular automation tool, uses YAML for its playbooks. Here is a simple example of an Ansible playbook using lists and dictionaries:

---
- name: Example Playbook
  hosts: all
  tasks:
    - name: Install a package
      apt:
        name: nginx
        state: present

    - name: Ensure a file is present
      copy:
        src: /path/to/source
        dest: /path/to/destination