I have a Python dict as below and I want to dump it into a YAML file. I want to dump those examples as a list of string examples instead of individual key (There is a pipe |
after examples
. How can I do that?
data = {'version': '1.0',
'food': [{'category': 'japanese', 'examples': ['sushi', 'ramen', 'sashimi']},
{'category': 'chinese', 'examples': ['hotpot', 'noodle', 'fried rice']}]}
yaml.SafeDumper.ignore_aliases = lambda *args : True
with open('food.yml', 'w', encoding = "utf-8") as yaml_file:
dump = yaml.safe_dump(data,
default_flow_style=False,
allow_unicode=False,
encoding=None,
sort_keys=False,
line_break=10)
yaml_file.write(dump)
Result
version: '1.0'
food:
- category: japanese
examples:
- sushi
- ramen
- sashimi
- category: chinese
examples:
- hotpot
- noodle
- fried rice
Expected
version: '1.0'
food:
- category: japanese
examples: |
- sushi
- ramen
- sashimi
- category: chinese
examples: |
- hotpot
- noodle
- fried rice