title: How to render a python dict as an html table with vertical columns
body: <p>I've got a python dict with where each key corresponds to a heading, and the list associated with each heading contains an arbitrary number of values:</p>
  
  <pre><code>data = { 
      "heading1": ['h1-val1', 'h1-val2', 'h1-val3', ],
      "heading2": ['h2-val1', ],
      "heading3": ['h3-val1', 'h3-val2', 'h3-val3', 'h3-val4', ],
  } 
  </code></pre>
  
  <p>I need to render this in a Django template as a table, where the values are listed vertically beneath each heading, with any missing values rendered as an empty table cell:</p>
  
  <pre><code>&lt;table&gt;
  &lt;thead&gt;
      &lt;tr&gt;
      &lt;th&gt;heading1&lt;/th&gt;
      &lt;th&gt;heading2&lt;/th&gt;
      &lt;th&gt;heading3&lt;/th&gt;
      &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
      &lt;tr&gt;
      &lt;td&gt;h1-val1&lt;/td&gt;
      &lt;td&gt;h2-val1&lt;/td&gt;
      &lt;td&gt;h3-val1&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
      &lt;td&gt;h1-val2&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;h3-val2&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
      &lt;td&gt;h1-val3&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;h3-val3&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;h3-val4&lt;/td&gt;
      &lt;/tr&gt;
  &lt;/tbody&gt;
  &lt;/table&gt;
  </code></pre>
  
  <p>What's the best way to achieve this?</p>
  
  <p>My first inclination is to rearrange the original dict into a 2D matrix, and just pass that into the template.  I'm sure I'm not the first to run into this kind of problem, though, and I'm curious how others have solved this problem.</p>
  
  <p><strong>UPDATE:</strong> Just for reference, here's my original solution to this problem (which I'm not very happy with).</p>
  
  <pre><code># Using the data dict from the question:
  size = max(len(data['heading1']), len(data['heading2']), len(data['heading3']))
  matrix = [[None, None, None] for i in range(size)] # initialize an empty matrix
  
  # manually copy the data into the appropriate column :(
  i = 0
  for item in data['heading1']:
      matrix[i][0] = item
      i += 1
  i = 0
  for item in data['heading2']:
      matrix[i][1] = item
      i += 1
  i = 0
  for item in data['heading3']:
      matrix[i][2] = item
      i += 1
  </code></pre>
  
  <p>I then passed the matrix into the template which looked like this:</p>
  
  <pre><code>&lt;table&gt;
  &lt;thead&gt;&lt;tr&gt;
      &lt;th&gt;heading1&lt;/th&gt;
      &lt;th&gt;heading2&lt;/th&gt;
      &lt;th&gt;heading3&lt;/th&gt;
  &lt;/tr&gt;&lt;/thead&gt;
  &lt;tbody&gt;
  {% for row in matrix %}
      &lt;tr&gt;
      {% for col in row %}
          &lt;td&gt;{% if col %}{{ col }}{% else %}&amp;nbsp;{% endif %}&lt;/td&gt;
      {% endfor %}
      &lt;/tr&gt;
  {% endfor %}
  &lt;/tbody&gt;
  &lt;/table&gt;
  </code></pre>