简体   繁体   English

在Django模板中获取字典键值

[英]Getting dictionary key values in django template

I have a dictionary created with Counter() in django. 我在Django中使用Counter()创建了一个字典。 I have a list named studentlist. 我有一个名为studentlist的列表。 I fill this list with some elements. 我用一些元素填充此列表。 Then i get the repeating elements number with Counter(). 然后我用Counter()得到重复元素的编号。

In my view : 在我看来 :

    studentlist = []
    for stu in studentslatetoclassthissemester:
        student = str(stu['student__std_no'])
        studentlist.append(student)

    studentsum = Counter(studentlist)

So studentsum is a dictionary as below. 因此,studentsum是如下的字典。

Counter({'0247': 4, '0044': 1, '0050': 1, '0241': 1, '0854': 1, '0245': 1, '0076': 1, '0234': 1}) 计数器({'0247':4,'0044':1,'0050':1,'0241':1,'0854':1,'0245':1,'0076':1,'0234':1 })

In the django template i am trying to get specifi key and values as below : 在django模板中,我试图获取特定的键和值,如下所示:

{% for key, value in studentsum.items %}                  
    {{key}} - {{value}}                  
{% endfor %}

But i get below error : 但我得到以下错误:

Exception Type: TypeError 异常类型:TypeError

Exception Value: 'int' object is not iterable 异常值:“ int”对象不可迭代

change this in view 改变这个观点

studentsum = Counter(studentlist)

to

studentsum = dict(Counter(studentlist))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM