'jinja 2 nested dictionaries to yaml

I'm trying to use jinja2 to output a nested dictionary to a yaml file. However I'm not sure how to access the nested dicts. With a flat dict for data I can use the below.

 - request:
        path: {{ path }}
        headers:
          origin: 'somedomain.com'
          user-agent: 'agent'
          referer: 'some.domain.com'
          authority: 'somedomain.com'
        data:
          {% for key, value in data.items() -%}
          {{ key }}: '{{ value }}'
          {%- endfor %}
      response:
        content:
          file: {{ content }}

However with a nested dict like below how do I achieve the output at the bottom?

{'toplevelkey1': {'nestedkey1': 'value1', 'nestedkey2': 123, 'nestedkey3': '55',
                 'nestedkey4': 1560}, 'toplevelkey34': 'df',
 'toplevelkey2': {'somekey12': 68, 'somekey58': False, 'somekey48': 3, 'somekey38': 'ADF',
                              'somekey39': 'St'}, 'toplevel34': 'T',
 'toplevel8': {'key33': 68, 'key94': 3, 'key83': 'T', 'key84': 'dog'}}

Required output

   - request:
    path: /some/path
    headers:
      origin: 'somedomain.com'
      user-agent: 'agent'
      referer: 'somedomain.com'
      authority: 'somedomain.com'
    data:
      toplevelkey1: 
        nestedkey1: 'value1'
        nestedkey2: '123
        ....      : ....
      toplevel34: 'T'
      toplevelkey2:
        'somekey12': 68
         .....     :  .....
  response:
    content:
      file: address.json


Solution 1:[1]

There is a somewhat smaller and more general solution:

# License: public-domain
import yaml # This is pyyaml

def yaml_pretty(d, indent=10):
    dump = yaml.dump(d)
    res = ""
    for line in dump.split("\n"):
        res += " " * indent + line + "\n"
    return res

This handles all types, e.g. also (nested) lists.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andreas Florath