简体   繁体   中英

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 :

The returned group is itself an iterator that shares the underlying iterable with groupby(). Because the source is shared, when the groupby() object is advanced, the previous group is no longer visible. 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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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