-2

I have a dictionary of list. eg :

result = {
    'a': ['x', 'y', 'z'],
    'b': ['p', 'q', 'r'],
    'c': ['m', 'n', 'o']
}

I want a, b and c to be the headings of my table and corresponding lists under that particular column.

I have passed the dictionary to html from cherrypy like this return tmpl.render(result = result)

Addition: This is the html code written

<table id="myTable"> {% for k,v in result.items() %}
    <th> {{ k }}</th>
    {% for val in v %}
    <tr>
        <td> {{ val }}</td>
    </tr>
    {% endfor %} {% endfor %}
</table>
  • 1
    What problem are you facing exactly? – Stephan Schrijver May 30 '19 at 13:10
  • @StephanSchrijver output is not in the desirable format. Headers will be on the left side and all the values of that particular heading which is in list is displayed in a single row. I want that dictionary in a html table with headings on the top and corresponding list element under that heading. – Anamadheya May 30 '19 at 14:47

1 Answers1

1

According to your logic, your code will now do the following (pseudo):

foreach key & value: add the key as a th,
then loop the value (because it is an array):
   add a new table row with a table cell with that 'nested' value.

That will result in the following output:

a
0
1
2
b
0
1
2
c
0
1
2

What you want to do, is (pseudo):

Create a tr for the headers
Loop all keys: add headers for all keys (a, b and c)
Foreach row (remember i (iterator))
    add a tr
    for each key (col) add value[i] as a td
    Close the tr
Close the table tag

I'll do my best writing this in your code (looking at the snippet you provided). Note: haven't tested this.

<table id="myTable"> 
    <tr>
      {% for k,v in results.items() %}
      <th> {{ k }}</th>
      {% endfor %}
    </tr>
    {% for i in range(0, len(results[a])) %}
    <tr>
      {% for k,v in results.items() %}
      <td>v[i]</td>
      {% endfor %}
    </tr>
    {% endfor %}
</table>

There are also libraries which do this for you: https://www.decalage.info/python/html (for example)

  • 1
    Thank You So much @StephanSchrijver !!!! It works but "len(results[a])" has to be passed from flask to view. – Anamadheya May 31 '19 at 06:50
  • Good to hear! There are some catches in the code I provided, but I'm sure you will figure that out. For example: what if len(results[a]) > len(results[b]). It will throw an exception. – Stephan Schrijver May 31 '19 at 07:53