How to render an ordered dictionary in django templates?

女生的网名这么多〃 提交于 2019-12-02 17:26:36
Yuji 'Tomita' Tomita

In views.py (Python2):

return render_to_response('results.html',
    {'data': sorted(results_dict.iteritems())})

Or in views.py (Python3):

return render_to_response('results.html',
    {'data': sorted(results_dict.items())})

In template file:

{% for key, value in data.items() %}
    <tr>
        <td> {{ key }}: </td> <td> {{ value }} </td>
    </tr>
{% endfor %}

Although changing the code in the view is preferable, you could also use the dictsort template tag:

https://docs.djangoproject.com/es/1.9/ref/templates/builtins/#std:templatefilter-dictsort

<table>
{% for key, value in data.items|dictsort:"0.lower" %}
    <tr>
        <td> {{ key }}: </td> <td> {{ value }} </td>
    </tr>
</table>

Another solution that worked very well for me and I think it's simplier. It uses OrderedDict() more info

In your views.py file add:

from collections import OrderedDict
def main(request):
    ord_dict = OrderedDict()
    ord_dict['2015-06-20'] = {}
    ord_dict['2015-06-20']['a'] = '1'
    ord_dict['2015-06-20']['b'] = '2'
    ord_dict['2015-06-21'] = {}
    ord_dict['2015-06-21']['a'] = '10'
    ord_dict['2015-06-21']['b'] = '20'
    return render(request, 'main.html', {'context': ord_dict})

Then in your template, you can do:

<table>
{% for key, value in context.items %}
    <tr>
        <td>{{ key }}</td>
        <td>{{ value.a }}</td>
        <td>{{ value.b }} </td>
    </tr>
{% endfor %}
</table>

This will return the keys of the dictionary in the same ordered that they were put in.

2015-06-20  1   2
2015-06-21  10  20

Refreshing old question but it was something that I've spent some time on as a programming noobie. It kinds of expands Yuji Tomita's answer.

How to sort dictionary that looks like this:

{model_A_object: {key: value, ...},...}

by model_A_object.field.

I fill it with for loop, and use it to store some aggregation, etc., data for queryset that I pass to template.

I've managed to do this (with Shubuntu from #Django help) by:

    result = sorted(dictionary.iteritems(), key= lambda (k, v) :  (k.field, v))

Then in the template:

    {% for model_A_object, data in result %}
        {% for key, value in data.items %}
            ...
        {% endfor %}
    {% endfor %}

Clean and easy, yet not that simple to figure out for beginner. Notice, that first for loop has result not result.items as it's not dictionary anymore, but list of tuples.

Hope it helps someone.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!