Using ruamel.yaml
posted by Anthon here, here are simple functions to convert yaml text to dict and vice versa that you can conveniently keep in your utility funcs:
from ruamel.yaml import YAML
from io import StringIO
def yaml2dict(y):
return YAML().load(y)
def dict2yaml(d):
output_stream = StringIO()
YAML().dump(d, output_stream)
return output_stream.getvalue()
Sample multi-line yaml to dict:
y = """
title: organelles absent in animal cells and present in a plant cell
question: |
Observe the following table and identify if the cell is of a plant or an animal
| Organelle | Present/Absent |
|---------- | -------------- |
| Nucleus | Present |
| Vacuole | Present |
| Cellwall | Absent |
| Cell membrane | Present |
| Mitochondria | Present |
| Chlorophyll | Absent |
answer_type: MCQ_single
choices:
- Plant
- Animal
points: 1
"""
d = yaml2dict(y)
d
output:
{'title': 'organelles absent in animal cells and present in a plant cell', 'question': 'Observe the following table and identify if the cell is of a plant or an animal\n| Organelle | Present/Absent | \n|---------- | -------------- | \n| Nucleus | Present |\n| Vacuole | Present |\n| Cellwall | Absent |\n| Cell membrane | Present |\n| Mitochondria | Present |\n| Chlorophyll | Absent |\n', 'answer_type': 'MCQ_single', 'choices': ['Plant', 'Animal'], 'points': 1}
Converting it back to yaml:
y2 = dict2yaml(d)
print(y2)
Output:
title: organelles absent in animal cells and present in a plant cell
question: |
Observe the following table and identify if the cell is of a plant or an animal
| Organelle | Present/Absent |
|---------- | -------------- |
| Nucleus | Present |
| Vacuole | Present |
| Cellwall | Absent |
| Cell membrane | Present |
| Mitochondria | Present |
| Chlorophyll | Absent |
answer_type: MCQ_single
choices:
- Plant
- Animal
points: 1
For completeness, install ruamel.yaml
by:
pip install ruamel.yaml