【发布时间】:2021-05-20 16:58:57
【问题描述】:
我试图在 Django 中只打印嵌套字典的第一个键和值。我可以用 python 做到这一点,但在 Django 模板语言中我的逻辑不起作用。
这是我在 DTL 中的代码
{% for key, value in data.items %}
<h1>Dictionary: {{ key }}</h1>
{% for key, value2 in value.items %}
<h3>Nested Dictionary-> {{ key }}: {{ value2 }}</h3> <!-- Its printing complete nested Dictionary-->
{% endfor %}
这是我的 view.py,它从 api 获取数据然后将 json 转换为字典
def home(request):
res = requests.get('https://covid19.mathdro.id/api/countries/india')
data = (res.json())
print(type(data))
return render(request, 'Caraousel/home.html', {'data':data})
不要被它需要的嵌套循环弄糊涂,因为有嵌套字典:
【问题讨论】:
-
如果你只想要字典中每个键的 value:number 对,嵌套循环有什么用?另外,避免在两个循环中为
key使用相同的名称 -
我正在使用嵌套循环,因为我想要的数据在嵌套字典中。请查看更新的问题,它显示了我正在转换为字典的原始 JSON 数据
标签: python python-3.x django django-templates