[Answered ]-Write a table with empty cells based on dictionary of values

2👍

Here’s the data structure.

[{<Type1>: 16,
  <Type2>: 10,
  <Type3>: 12,
  <Type4>: 7,
  <Type5>: 0,
  'assemblage': <Assemblage1>},
 {<Type1>: 85,
  <Type2>: 18,
  <Type3>: 21,
  <Type4>: 12,
  <Type5>: 2,
  'assemblage': <Assemblage2>},
 ...]

The problem is that the resulting table must be generated in row order, and this list of dictionaries is in column order. So the list of dicts must be pivoted into row-major order.

from collections import defaultdict
titles = []
cells = defaultdict(list)
for x,col in enumerate(table):
    titles.append( col['assemblage'] )
    for rk in col:
        if rk == 'assemblage': continue # skip the title
        cells[rk][x]= col[rk]

Also, it helps to formalize the results as a list of lists; dictionaries have no inherent order.

final= []
for name in sorted( cells.keys() ):
    final.append( cells[name] )

Here’s the template to render titles and final as a table.

<table>
  <tr>
    {% for t in titles %}<th>{{t}}</th>{% endfor %}
  </tr>
  {% for row in final %}
  <tr>
      {% for cell in row %}<td>{{cell}}</td>{% endfor %}
  </tr>
  {% endfor %}
</table>
👤S.Lott

Leave a comment