【问题标题】:How do you write out the value of a dictionary key using Django with Python?如何使用 Django 和 Python 写出字典键的值?
【发布时间】:2017-11-13 08:40:13
【问题描述】:

我想知道你如何将它合并到 html 中。我现在拥有的是以下内容。

{% for u in list %}
    {{ u }} <br>
{% endfor %}

而我想要的是这些方面的东西-

{% for u in list %}
    {{ u }} <br>
    {{ u.value }} <br>
{% endfor %}

谢谢大家!

编辑:示例如下所示-

Apple
10
---
Banana
4
---
Orange
3
---
Pear
1
---

【问题讨论】:

  • 他们每个人的输出如何不符合您的期望,您对它的外观有何期望?请提供样品。
  • 我添加了一个例子。 @Chris,我知道我可能是对的。我不是
  • “我知道我可能是对的”——那你为什么不直接试试?!这比在 Stack Overflow 上输入问题要快得多!
  • @NickTheInventor 在这种情况下“它不起作用”是什么意思?提供这些详细信息对于读者了解正在发生的事情以了解如何为您提供帮助至关重要。根据您提供的代码,输出看起来如何,它们看起来如何向您表明它有问题?此外,字典迭代应该使用for k, v in your_dict.items()
  • 请阅读How to Ask。到目前为止,您还没有非常有效地提出问题。

标签: python html django


【解决方案1】:

给你。

{% for key, value in list.items %}
    {{ key }} <br>
    {{ value }} <br>
    --- <br>
{% endfor %}

您也可以通过这种方式访问​​嵌套项。在您看来:

grocery_list = {
    'Apples': {'Red Disgusting': 5, 'Granny Smith': 3}, 
    'Snack Food': {'Spam': 4, 'Eggs': 1}
}

在您的模板中:

{% for food_type, list in grocery_list.items %}
    <h3>{{ food_type }}</h3
    {% for item, quantity in list.items %}
        <p>{{ item }}: {{ quantity }}</p>
    {% endfor %}
{% endfor %}

结果:

苹果

红色恶心:5

史密斯奶奶:3

零食

垃圾邮件:4

鸡蛋:1 个

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多