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

2024-04-20 16:33:53 发布

您现在位置:Python中文网/ 问答频道 /正文

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

如何将其显示到视图中的表中?


Tags: 视图字典value
2条回答

取决于你想怎么做。在Django模板中,访问键的方式与访问方法的方式相同。也就是说,Python代码类似

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

变成

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

在Django模板中。

回答问题here

总之,您可以像访问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>

相关问题 更多 >