How to Convert YAML to a Python Dictionary?

Estimated read time 1 min read

You can use the PyYAML library to convert YAML data to a Python dictionary. Here’s an example code snippet:

import yaml

# YAML data as a string
yaml_data = """
key1: value1
  - item1
  - item2
  subkey1: subvalue1
  subkey2: subvalue2

# Parse the YAML data into a Python dictionary
data_dict = yaml.safe_load(yaml_data)

# Print the resulting dictionary

In this example, we start with a YAML data string (yaml_data). We use the safe_load() function of the yaml module to parse the YAML data into a Python dictionary (data_dict). Finally, we print the resulting dictionary.

The safe_load() function is used instead of load() to prevent arbitrary code execution, as load() can execute arbitrary code if the YAML data contains Python objects. If you’re sure that your YAML data doesn’t contain any malicious code, you can use load() instead.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply