Convert Python dictionary to YAML using PyYAML

In this tutorial, you are going to learn how to convert a Python dictionary into YAML format with the help of the PyYAML Python module.

In PyYAML, the formatting style for collections (such as lists or dictionaries) is automatically selected based on their content. Specifically, if a collection contains nested collections, PyYAML will use the block style for serialization. If there are no nested collections, it will use the flow style.

However, you can override this default behavior and ensure that all collections are always serialized in the block style. To do this, you need to set the default_flow_style parameter to False in the dump() method. For example:

print(yaml.dump(yaml.load(document), default_flow_style=False))

This will format the collections in the block style, which is generally more readable for complex data structures. Here’s how it will look:

a: 1
b:
  c: 3
  d: 4

Conversion from Python dictionary to yaml with step-by-step example

Converting a Python dictionary to a YAML format involves serializing the dictionary. This can be done using the yaml module in Python. If you haven’t already installed the pyyaml package, you can do so using pip:

pip install pyyaml

Once installed, here is an example of how you can convert a Python dictionary to YAML:

import yaml

# Example dictionary
my_dict = {
    'name': 'John Doe',
    'age': 30,
    'married': True,
    'children': ['Alice', 'Bob'],
    'address': {
        'street': '123 Main St',
        'city': 'Anytown',
        'state': 'CA'
    }
}

# Convert to YAML
yaml_str = yaml.dump(my_dict, default_flow_style=False)

print(yaml_str)

This code will output the dictionary in YAML format. The default_flow_style=False argument ensures that the YAML is output in the block style, which is more readable for complex structures.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top