django template: get data from dictionary

时间:2016-02-12 20:07:50

标签: python django dictionary django-templates

I'm new to django and Im tring to get data out of dictionary

variable number_of_books has dictionary as shown below

[{'num_books': 3, 'name': u'comp science'}, {'num_books': 1, 'name': u'electronics'}, {'num_books': 0, 'name': u'civil'}]

In my django template I tried to get data, but could not succeed

{% for key, value in number_of_books.items %}
    <li>{{key}} - {{value}}</li>
{% endfor %}

please help in getting data in my template

Thanks in advance

1 个答案:

答案 0 :(得分:3)

You are having a list of dicts not a dict, so looping like that wouldn't work. You should do:

{% for item in number_of_books %}
    <li>{{ item.num_books }} - {{ item.name }}</li>
{% endfor %}