Search code examples
pythonyamlpyyaml

Outputting yaml in dict format


I have a list of dict that looks like this

data = {'items': [{'id': '1', 'desc': 'Item 1', 'cat': 'cat1'}], 'categories': [{ 'id': 'cat1', 'desc': 'category number 1' }]}

I want to dump this in the following yaml format

---
items:
    - { id: 'it1', desc: 'item number 1', cat: 'cat1' }
categories:
    - { id: 'cat1', desc: 'category number 1' }

using yaml.dump(data) outputs a yaml in the following format

categories:
- desc: category number 1
  id: cat1
items:
- cat: cat1
  desc: Item 1
  id: '1'

What do I need to add to change this? I have tried setting the default_flow_style=False with no difference.


Solution

  • In PyYAML, the option default_flow_style has three different values:

    • True: everything is dumped in flow style
    • False: everything is dumped in block style
    • None: only the lowest level of dicts and lists is dumped in flow style

    We changed the default from None to False in version 5.1 because many people complained about it. So you need default_flow_style=None.