简体   繁体   English

Django模板-如何迭代和访问字典?

[英]Django Template - How to Iterate and access a dictionary?

I have a dictionary to iterate over, I printed it on my webpage and got this: 我有一本字典要遍历,将其打印在我的网页上并得到:

dict = {
    u'256': <itertools._grouper object at 0x8361d0e90>,
    u'59': <itertools._grouper object at 0x83607c110>,
    u'59': <itertools._grouper object at 0x83607c050>,
    u'1975555': <itertools._grouper object at 0x8361bc490>,
    u'91': <itertools._grouper object at 0x836162110>
}

How can I access the values of this object in dictionary? 如何在字典中访问此对象的值? Here is something I have tried: 这是我尝试过的:

{% for code, codelist in dict.items %}
    {% for innerlists in codelist %}
        // Here I want to display the values in the dict's object
    {% endfor %}
{% endfor %}

If your're user itertools.groupby , pay attention to the note in the docs pages : 如果您是itertools.groupby用户,请注意docs页面中的注释:

The returned group is itself an iterator that shares the underlying iterable with groupby(). 返回的组本身就是一个与groupby()共享基础可迭代项的迭代器。 Because the source is shared, when the groupby() object is advanced, the previous group is no longer visible. 因为源是共享的,所以当前进groupby()对象时,先前的组不再可见。 So, if that data is needed later, it should be stored as a list : 因此, 如果以后需要该数据,则应将其存储为列表

groups = []
uniquekeys = []
data = sorted(data, key=keyfunc)
for k, g in groupby(data, keyfunc):
    groups.append(list(g))      # Store group iterator as a list
    uniquekeys.append(k)

(Bolds added) (加粗体)

Don't use dict as a varname, and when creating this dict, convert the _grouper values to list . 不要将dict用作_grouper ,在创建此dict时,请将_grouper值转换为list Nothing seems wrong with your template. 您的模板似乎没有问题。

{% for item in dict%}
//do stuff
{% endfor %}

should work unless you dict has a nested attribute "items" that you want to iterate through. 除非您的字典具有要迭代的嵌套属性“项目”,否则它应该可以工作。

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

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