gpt4 book ai didi

python - 如何在 django 模板中的字典中遍历字典?

转载 作者:IT老高 更新时间:2023-10-28 21:06:14 24 4
gpt4 key购买 nike

我的字典是这样的(字典中的字典):

{'0': {
'chosen_unit': <Unit: Kg>,
'cost': Decimal('10.0000'),
'unit__name_abbrev': u'G',
'supplier__supplier': u"Steve's Meat Locker",
'price': Decimal('5.00'),
'supplier__address': u'No\r\naddress here',
'chosen_unit_amount': u'2',
'city__name': u'Joburg, Central',
'supplier__phone_number': u'02299944444',
'supplier__website': None,
'supplier__price_list': u'',
'supplier__email': u'ss.sss@ssssss.com',
'unit__name': u'Gram',
'name': u'Rump Bone',
}}

现在我只是想在我的模板上显示信息,但我很挣扎。我的模板代码如下:

{% if landing_dict.ingredients %}
<hr>
{% for ingredient in landing_dict.ingredients %}
{{ ingredient }}
{% endfor %}
<a href="/">Print {{ landing_dict.recipe_name }}</a>
{% else %}
Please search for an ingredient below
{% endif %}

它只是在我的模板上显示“0”?

我也试过了:

{% for ingredient in landing_dict.ingredients %}
{{ ingredient.cost }}
{% endfor %}

这甚至不显示结果。

我想也许我需要更深入地迭代一个级别,所以尝试了这个:

{% if landing_dict.ingredients %}
<hr>
{% for ingredient in landing_dict.ingredients %}
{% for field in ingredient %}
{{ field }}
{% endfor %}
{% endfor %}
<a href="/">Print {{ landing_dict.recipe_name }}</a>
{% else %}
Please search for an ingredient below
{% endif %}

但这并没有显示任何内容。

我做错了什么?

最佳答案

假设您的数据是 -

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

您可以使用 data.items() 方法来获取字典元素。请注意,在 django 模板中,我们不会放置 ()。还有一些用户提到 values[0] 不起作用,如果是这种情况,请尝试 values.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>

我很确定您可以将此逻辑扩展到您的特定字典。


按排序顺序迭代 dict 键 - 首先我们在 python 中排序,然后在 django 模板中迭代和渲染。

return render_to_response('some_page.html', {'data': sorted(data.items())})

在模板文件中:

{% for key, value in data %}
<tr>
<td> Key: {{ key }} </td>
<td> Value: {{ value }} </td>
</tr>
{% endfor %}

关于python - 如何在 django 模板中的字典中遍历字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8018973/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com