Python YAML Examples

I will list a few practical Python YAML examples in this vlog post. This should cover basic to advanced examples and troubleshooting steps and FAQs.

Python YAML – Requirement – pyyaml module.

This guide is depending on Pythn module, pyyaml. You can install it by running:

pip install pyyaml

You can find a more detailed example here, on How to install YAML module

Python YAML – Optional VENV setup

We recommend using a virtual environment for your project. If you would like to know the steps for creating venv, please refer to these guides:

Python YAML – Reading One Key Value

Let’s consider you have a YAML file named codetryout_data.yaml with the following content:

name: CodeTryout

Now, lets retrieve the value of the key, name with our code.

Creating a file called, demo.py and running

import yaml
yaml_file = "codetryout_data.yaml"
with open(yaml_file, 'r') as file:
    data = yaml.safe_load(file)
    name_value = data.get('name')
    print(name_value)

Test run:

python demo.py      

CodeTryout

Python YAML – Multiple key-value pair

Here’s a simple example of how to read a key and its corresponding value from a YAML file:

key1: CodeTryout
key2: DevOps
key3: Python
key4: YAML

Creating a file called, demo.py and running

import yaml
yaml_file = "codetryout.yaml"

with open(yaml_file, 'r') as file:
    data = yaml.safe_load(file)
    for key, value in data.items():
        print(f"{key}: {value}")

Demo output:

python demo.py
  
key1: CodeTryout
key2: DevOps
key3: Python
key4: YAML

Python YAML – Printing Nested Dictionary / groups

Example YAML File

group:
  blue:
    key1: value1
    key2: value2
  orange:
    key1: o_value1
    key2: o_value2
  red:
    key1: r_value1
    key2: r_value2

Example code

import yaml

def print_all_keys_and_values(yaml_file):
    with open(yaml_file, 'r') as file:
        data = yaml.safe_load(file)
        for group, group_data in data['group'].items():
            print(f"Group: {group}")
            for key, value in group_data.items():
                print(f"  {key}: {value}")
            print()

print_all_keys_and_values("codetryout_demo.yaml")

This code reads the YAML file, correctly accesses the nested dictionary under the “group” key, and prints the keys and values as expected.

Code Walkthrough:

Use the yaml.safe_load function from the pyyaml library to load the YAML file’s contents into a Python dictionary.

To read a specific key-value pair, use the .get() method on the dictionary to access the value associated with the desired key. To print all keys and values, iterate through the dictionary‘s items using a loop and print them in the desired format.

Example output


Group: blue
  key1: value1
  key2: value2

Group: orange
  key1: o_value1
  key2: o_value2

Group: red
  key1: r_value1
  key2: r_value2

Python YAML – Getting specific Group / Key / Value

Next, let us see how to get specific group / key / value from the above YAML file

import yaml

def get_value(yaml_file, group, key):
    with open(yaml_file, 'r') as file:
        data = yaml.safe_load(file)
        if 'group' in data and group in data['group'] and key in data['group'][group]:
            return data['group'][group][key]
    return None

yaml_file = "codetryout_demo.yaml"
group_name = "red"
key_name = "key2"

value = get_value(yaml_file, group_name, key_name)
if value is not None:
    print(f"The value of '{key_name}' in '{group_name}': {value}")
else:
    print(f"'{key_name}' not found in '{group_name}' or '{group_name}' not found in the YAML file.")

Example Output

The value of 'key2' in 'red': r_value2The value of 'key2' in 'red': r_value2

Python YAML – PyYAML efficiency

Reading YAML using the pyyaml library is generally considered efficient and widely used for YAML parsing in Python. However, like any library, its efficiency depends on factors such as the size of the YAML file, the complexity of the data structure, and the machine’s processing capabilities.

Here are some points to consider regarding the efficiency of pyyaml:

  • Parsing Time: For small to medium-sized YAML files, the parsing time with pyyaml is typically fast and efficient. It can handle simple YAML structures quickly and accurately.
  • Memory Usage: For large YAML files or complex data structures, pyyaml may consume significant memory, especially when loading the entire YAML content into a Python dictionary. If memory usage is a concern, consider using other libraries like ruamel.yaml, which offers more memory-efficient options.
  • Cython Implementation: pyyaml has a Cython implementation, which provides a performance boost. This makes it faster than pure Python-based YAML parsers.
  • Compatibility: pyyaml is compatible with both Python 2 and Python 3, making it a popular choice for cross-version compatibility.
  • Feature-Rich: pyyaml provides a wide range of features, including support for custom types, round-trip preservation of comments and styles, and various loading/dumping options.

While pyyaml is efficient for most use cases, you might explore other YAML parsers if you have specific requirements, such as improved memory efficiency or faster parsing times for exceptionally large YAML files.

Keep in mind that efficiency is relative to your specific use case. Before deciding on a YAML parser, consider your project’s needs and test performance with representative data to ensure it meets your expectations.