0

I wish to print a table in an html with Flask(jinja) from a nested dict:

Python part:

@app.route("/")

def index():

#the nested dict exemple:
    dict_temp = {0: {'symbol': 'NFLX', 'name': 'Netflix', 'share': '6', 'price': '123', 'total':
''}, 1: {'symbol': 'NFLX', 'name': 'Netflix', 'share': '6', 'price': '123', 'total': ''}, 2: {'symbol': 'NFLX', 'name': 'Netflix', 'share': '6', 'price': '123', 'total': ''}}

    parent_dict = dict_temp

    return render_template("test.html", parent_dict = parent_dict)

Jinja template with the table:

 <table style="width:100%">

  <tr>
    <th>Symbol</th>
    <th>Name</th>
    <th>Shares</th>
    <th>Price</th>
    <th>Total</th>
  </tr>

    {% for dict_item in parent_dict %}
    <tr>
        {% for key, value in dict_item.items() %}
            <td>{{value}}</td>
        {% endfor %}
    </tr>
    {% endfor %}

</table>

The code work with this python:

parent_dict = [{'A':'item1 A','B':'item1 B'},{'a':'item2 A','b':'Item2 B', 'c':'Item2 C'}]

How could I loop with jinja and a nested dict of this type:

{1:{'A':'item1 A','B':'item1 B'}, 2:{'a':'item2 A','b':'Item2 B', 'c':'Item2 C'}, ... }

Or maybe I have to build my input differently?

vvvvv
  • 25,404
  • 19
  • 49
  • 81
saquiel
  • 476
  • 1
  • 5
  • 14

1 Answers1

0

There are ways to iterate through nested dict in python but I dont think this can be done in templates in flask.

As you've suggested you can make use of the list of dict method as you've shown above.

For example

{1:{'A':'item1 A','B':'item1 B'}, 2:{'a':'item2 A','b':'Item2 B', 'c':'Item2 C'}, ... }

becomes

[{'A':'item1 A','B':'item1 B'}, {'a':'item2 A','b':'Item2 B', 'c':'Item2 C'}, ... ]

Iterate through in the template:

    {% for dict_item in list %}
       {% for key, value in dict_item.items() %}
          <h1>Key: {{key}}</h1>
          <h2>Value: {{value}}</h2>
       {% endfor %}
    {% endfor %}

You can do the following to convert dict of dict to list of dict

list_of_dics = [value for value in dic_of_dics.values()].

See here

AzyCrw4282
  • 7,222
  • 5
  • 19
  • 35
  • 1
    Thanks you so much. You save my day. All is working so well. Could you correct me if I'm wrong: Jinja deal easily with list of dict (not with dict of dict). Is that it? – saquiel Feb 20 '20 at 15:39
  • From what I looked up, this was what I learned. Others opinion may differ! – AzyCrw4282 Feb 20 '20 at 16:05