【问题标题】:How do I access only first element in nested dictionary in Django template?如何在 Django 模板中仅访问嵌套字典中的第一个元素?
【发布时间】: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


【解决方案1】:

因为这是您的数据:

'Dictionary: confirmed': {'value': 10937320, 'detail': 'https://covid19.mathdro.id/api/countries/india/confirmed'}
    
'Dictionary: recovered': {'value': 10644858, 'detail': 'https://covid19.mathdro.id/api/countries/india/recovered'}
    
'Dictionary: deaths': {'value': 155913, 'detail': 'https://covid19.mathdro.id/api/countries/india/deaths'}
    
'Dictionary: lastUpdate': 2021-02-17T18:23:40.000Z

在模板中渲染之前,您可以根据需要处理数据。所以让我们更新我们的嵌套字典来保存第一项的值:

def home(request):
    res = requests.get('https://covid19.mathdro.id/api/countries/india')
    data = (res.json())

    for key, value in data.items():
        if type(value) is dict:
            # Create iterator to get only first item from nested dictionary
            item_iterator = iter(value.items())
            first_item = next(item_iterator)

            # Update key containing only first item
            data[key] = {first_item[0]: first_item[1]}
    
    return render(request, 'Caraousel/home.html', {'data':data})

这样处理后的数据是这样的:

{'confirmed': {'value': 10937320},
 'recovered': {'value': 10644858},
 'deaths': {'value': 155913},
 'lastUpdate': '2021-02-17T19:23:59.000Z'}

现在您可以使用现有代码获得所需的内容。

【讨论】:

  • 嘿,非常感谢你的努力,但我想我的形象是模糊理解请再看看我更新。首先确认的是字典里面有另一个字典的值:数字,详细信息:url。
  • 在模板中渲染数据之前如何处理?
  • @NehaSharma 已编辑答案,检查是否能解决问题
  • 我只是做了同样的事情,然后我来这里更新,但只是看到你的回答哈哈。谢谢您,我们的逻辑几乎相同,并且工作正常。感谢您的帮助:-)
猜你喜欢
  • 2017-03-09
  • 2014-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-04
  • 2020-10-25
相关资源
最近更新 更多