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:
JavaScript
x
5
1
dict = {
2
key_1: {a: 1, b: 2, c: 3},
3
key_2: {a: 11, b: 12, c: 13},
4
}
5
And I want the table to look like:
JavaScript
1
6
1
| key_1 | key_2 |
2
| ---------- | ------------ |
3
| a | b | c | a | b | c |
4
| ---------- | ------------ |
5
| 1 | 2 | 3 | 11 | 12 | 13 |
6
The closest I have come is:
JavaScript
1
18
18
1
<table>
2
<tr>
3
{% for k1 in dict.keys() %}
4
<td>{{ k1 }}</td>
5
</tr>
6
<tr>
7
{% for k2, value in dict[k1].items() %}
8
<td> {{ k2 }} </td>
9
{% endfor %}
10
</tr>
11
<tr>
12
{% for k2, value in dict[k1].items() %}
13
<td> {{ value }} </td>
14
{% endfor %}
15
{% endfor %}
16
</tr>
17
</table>
18
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
.)
JavaScript
1
22
22
1
<table>
2
<tr>
3
{% for k, d2 in dct.items() %}
4
<td colspan="{{ d2|length }}">{{ k }}</td>
5
{% endfor %}
6
</tr>
7
<tr>
8
{% for d2 in dct.values() %}
9
{% for k2 in d2 %}
10
<td>{{ k2 }}</td>
11
{% endfor %}
12
{% endfor %}
13
</tr>
14
<tr>
15
{% for d2 in dct.values() %}
16
{% for v2 in d2.values() %}
17
<td>{{ v2 }}</td>
18
{% endfor %}
19
{% endfor %}
20
</tr>
21
</table>
22