Search code examples
pythonflaskjinja2template-engine

Looping through a nested dictionary (Jinja2, Flask)


I have spent way too much time trying to figure this out. I have a dictionary like the following:

{'asset_1': {'scenario_1':10%, 'scenario_2':-20%}, 'asset_2': {'scenario_1':-11%, 'scenario_2':30%}, 'asset_3': {'scenario_1':15%, 'scenario_2':22%}, 'asset_4': {'scenario_1':-13%, 'scenario_2':30%}}

What I need now to do is loop through the each asset, and then through each scenario and fill this in, in the table. But I cannot access the outer loop's asset name in the innermost. I can access the index however, through {% set asset_loop = loop %}, and then say {{asset_loop.index}}, but this is not helpful, because I would have to know ahead of calling {{asset_loop.index}}, which index corresponds to which asset (so that I create a dictionary like the following: {0: {'scenario_1':...}, 1: {'scenario_1':,...},..}, but I cannot guarantee the order in the dictionary!

This is what I have atm, which does not work, clearly, but shows what I want to achieve:

{% for asset in (raw_results["risk_scenarios"].keys() | list) %}
     {% set asset_loop = loop %}
     <tr>
         <th>{{asset}}</th>
         <td>weight</td>

         {% for scenario in raw_results["risk_scenarios"][{{asset}}] %}
             <td>{{raw_results["risk_scenarios"][{{asset}}][{{scenario}}]}}</td>
         {% endfor %}
     </tr>
{% endfor %}

Solution

  • You don't have to use Jinja templating syntax inside markup. Try using asset as ordinary variable: {% for scenario in raw_results["risk_scenarios"][asset] %}

    The same goes for scenario