简体   繁体   English

如何将 python 字典的键显示为 HTML 表头,并将每个键的值显示为该表 header 下的一行?

[英]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.我目前正在一个 django 项目中工作,在该项目中,我使用 pandas 库进行了一些数据分析,并希望将数据(已转换为字典)显示为 HTML 表。

dictionary that I want to display:我要显示的字典:

my_dict = {
    'id': [1, 2, 3, 4, 5],
    'product_name': [product1, product2, product3, product4, product5],
    'value': [200, 400, 600, 800, 1000],
    'available_qty': [1, 2, 3, 2, 4]
}

I want to display the above dictionary like this table in django template.我想在 django 模板中像这个表一样显示上面的字典。

id ID product_name产品名称 value价值 available_qty可用数量
1 1个 product1产品1 200 200 1 1个
2 2个 product2产品2 400 400 2 2个
3 3个 product3产品3 600 600 3 3个
4 4个 product4产品4 800 800 2 2个
5 5个 product5产品5 1000 1000 4 4个

I have tried the below code.我试过下面的代码。

<table>
    <thead><h2><b>my dictionary</b></h2></thead>
        {% for key, values in my_dict.items %}
            <th><b>{{ key }}</b></th>
            {% for value in values %}   
                <tr>
                    {{value}}
                </tr>   
            {% endfor %}
        {% endfor %}
</table>

I get the results as,我得到的结果是,

HTML 表格结果

(There is some space between each row displayed in the table) (表格中显示的每一行之间有一些空间)

Better first convert to list of rows (using zip() ) and send this to template最好先转换为行列表(使用zip() )并将其发送到模板

my_dict = {
    'id': [1, 2, 3, 4, 5],
    'product_name': ['product1', 'product2', 'product3', 'product4', 'product5'],
    'value': [200, 400, 600, 800, 1000],
    'available_qty': [1, 2, 3, 2, 4]
}

all_headers = list(my_dict.keys())

all_rows = list(zip(*my_dict.values()))

print(all_headers)
for row in all_rows:
    print(row)

Result:结果:

['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)

And then template could be (but I didn't test it)然后模板可能是(但我没有测试它)

<h2>my dictionary</h2>

<table>

    <thead>
      <tr>
      {% for header in all_headers %}
        <th>{{ header }}</th>
      {% endfor %}
      <tr>
    </thead>
    
    <tbody>
      {% for row in all_rows %}
      <tr>
         {% for value in row %}   
            <td>{{ value }}</td>   
         {% endfor %}
      <tr>
      {% endfor %}
    </tbody>
    
</table>

EDIT:编辑:

If you use pandas then you could use df.to_html() to generate table如果您使用pandas那么您可以使用df.to_html()生成表格

import pandas as pd

df = pd.DataFrame(my_dict)

html_table = df.to_html(index=False)

print(html_table)

and it gives HTML similar to code from my previous template它给出了 HTML 类似于我之前模板中的代码

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th>id</th>
      <th>product_name</th>
      <th>value</th>
      <th>available_qty</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>product1</td>
      <td>200</td>
      <td>1</td>
    </tr>
    <tr>
      <td>2</td>
      <td>product2</td>
      <td>400</td>
      <td>2</td>
    </tr>
    <tr>
      <td>3</td>
      <td>product3</td>
      <td>600</td>
      <td>3</td>
    </tr>
    <tr>
      <td>4</td>
      <td>product4</td>
      <td>800</td>
      <td>2</td>
    </tr>
    <tr>
      <td>5</td>
      <td>product5</td>
      <td>1000</td>
      <td>4</td>
    </tr>
  </tbody>
</table>

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; )您可以将html_table发送到模板,并且必须使用safe选项显示它(因此它不会将< >转换为&lg; , &gt;

{{ html_table | safe }}

In your template在你的模板中

  • Load filters加载过滤器
{% load filter %}
{% block body %}
    <table class="table table-hover">
        <thead>
            <tr>
                {% for key in my_dict %}
                    <th scope="col">{{ key }}</th>
                {% endfor %}
            </tr>
        </thead>
        <tbody>
            {% for i in my_dict|RANGE %}
                <tr>
                    {% for key, value in my_dict.items %}
                        {% if forloop.counter0 < my_dict|length %}
                            <td>{{ value|items:i }}</td>
                        {% endif %}
                    {% endfor %}
                </tr>
            {% endfor %}
        </tbody>
    </table>
{% endblock %}

In project/app/ create a folder called templatetags在 project/app/ 创建一个名为 templatetags 的文件夹

  • In your templatetags folder there will be在你的 templatetags 文件夹中会有
    • init .py初始化.py
    • filters.py过滤器.py
  • put the following code in filters.py将以下代码放入 filters.py
from django import template

register = template.Library()


@register.filter
def RANGE(dictionary):
    length = 0
    for key, value in dictionary.items():
        if length < len(value):
            length = len(value)
    return list(range(length))


@register.filter
def items(List, index):
    return List[index]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当行内容是相关键的键值(每列的标题)时,如何用python在csv中编写嵌套字典? - How to write nested dictionary in csv with python when the row contents are key values of related key (the header of each column)? Python:将字典键解析为表中的值 - Python: parsing dictionary keys to values in a table python:字典键作为行索引,值作为列标题。 如何使用字典引用并选择 df 中的特定值? - python: Dictionary key as row index, values as column headers. How do I refer back and select specific values in a df using a dictionary? Python / Django - 如何将字典中的值列表 map 转换为 HTML 表? - Python / Django - How to map a list of values in a dictionary to a HTML table? 如何对字典 python 的每个键的值进行排序? - How to sort the values of each key of dictionary python? 提取 HTML 表数据从 email 到 csv 文件,第一列值到行标题,使用 ZA7F5F35426B928727111 - Extracting HTML table data from email to csv file, 1st column values to row headers, using Python 按每个键下的值数对字典进行排序 - Sort dictionary by number of values under each key 如何将 numpy 数组中的每一行分配到字典 python 中的键中 - How to assign each row in a numpy array into keys in dictionary python 将 Python 字典输入到 html 表中 - Python dictionary in to html table 当行的 html 标签未嵌套在表头标签下时,在表头下方刮取信息行 - Scraping row of info underneath a table header when the html tags for the row are not nested under the header tag
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM