Skip to content
Advertisement

How to display the keys of a python dictionary as HTML table headers and values of each key as a row under that table header?

I’m currently working in a django project in which I do some data analysis using pandas library and want to display the data (which is converted into a dictionary) as a HTML table.

dictionary that I want to display:

JavaScript

I want to display the above dictionary like this table in django template.

id product_name value available_qty
1 product1 200 1
2 product2 400 2
3 product3 600 3
4 product4 800 2
5 product5 1000 4

I have tried the below code.

JavaScript

I get the results as,

HTML table result

(There is some space between each row displayed in the table)

Advertisement

Answer

Better first convert to list of rows (using zip()) and send this to template

JavaScript

Result:

JavaScript

And then template could be (but I didn’t test it)

JavaScript

EDIT:

If you use pandas then you could use df.to_html() to generate table

JavaScript

and it gives HTML similar to code from my previous template

JavaScript

And you can send html_table to template and you have to display it with option safe (so it will not convert < > to &lg;, &gt;)

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement