Django视图:如何从字典中显示数据

1 投票
3 回答
10436 浏览
提问于 2025-04-16 07:48

我有一个字典,内容像这样:{'a':{'c':2, 'd':4 }, 'b': {'c':'value', 'd': 3}}

我该怎么把它显示成一个表格呢?

3 个回答

1

我遇到过类似的问题,我是这样解决的:

使用PYTHON:

views.py
#I had a dictionary with the next structure
my_dict = {'a':{'k1':'v1'}, 'b':{'k2': 'v2'}, 'c':{'k3':'v3'}}
context = {'renderdict': my_dict}
return render(request, 'whatever.html', context)

使用HTML:

{% for key, value in renderdict.items %}
    <h1>{{ key }}</h1>
    
    {% for k, v in value.items %}
      <h1>{{ k }}</h1>
      <h1 > {{ v }}</h1>
    {% endfor %}

{% endfor %}

The outputs would be 
{{ key }} = a 
{{ k }} = k1 
{{ v }} = v1  #and so forth through the loop.
3

问题的答案可以在 这里 找到:

简单来说,你可以像访问普通的 Python 字典那样来访问这些代码。

data = {'a': [ [1, 2] ], 'b': [ [3, 4] ],'c':[ [5,6]] }

你可以使用 dict.items() 方法来获取字典里的元素:

<table>
<tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
</tr>

{% for key, values in data.items %}
<tr>
    <td>{{key}}</td>
    {% for v in values[0] %}
    <td>{{v}}</td>
    {% endfor %}
</tr>
{% endfor %}
</table>
2

这要看你想怎么做。在Django的模板中,访问键的方式就像调用一个方法一样。也就是说,像下面这样的Python代码

print my_dict['a']['c']    # Outputs: 2

在Django模板中会变成

{{ my_dict.a.c }}    {# Outputs: 2 #}

撰写回答