I am scratching my head trying to correctly format a table from a nested dict in Jinja2, but having no luck.
The dict is something like this:
dict = { key_1: {a: 1, b: 2, c: 3}, key_2: {a: 11, b: 12, c: 13}, }
And I want the table to look like:
| key_1 | key_2 | | ---------- | ------------ | | a | b | c | a | b | c | | ---------- | ------------ | | 1 | 2 | 3 | 11 | 12 | 13 |
The closest I have come is:
<table> <tr> {% for k1 in dict.keys() %} <td>{{ k1 }}</td> </tr> <tr> {% for k2, value in dict[k1].items() %} <td> {{ k2 }} </td> {% endfor %} </tr> <tr> {% for k2, value in dict[k1].items() %} <td> {{ value }} </td> {% endfor %} {% endfor %} </tr> </table>
But this doesn’t work. I am having trouble assigning the k1 variable without also having to extend the loop in a way that ruins the layout of the table. I would rather not have to rearrange the dict or split it into several dicts.
Can I convert a dict like the one I have to a table of that structure in Jinja2? If yes, how?
Advertisement
Answer
I did not test my solution, there might be typos, but main points are:
colspan
for proper formatting- nested loops (inner and outer dict)
(dict
should not be used as a variable name, renamed todct
.)
<table> <tr> {% for k, d2 in dct.items() %} <td colspan="{{ d2|length }}">{{ k }}</td> {% endfor %} </tr> <tr> {% for d2 in dct.values() %} {% for k2 in d2 %} <td>{{ k2 }}</td> {% endfor %} {% endfor %} </tr> <tr> {% for d2 in dct.values() %} {% for v2 in d2.values() %} <td>{{ v2 }}</td> {% endfor %} {% endfor %} </tr> </table>