Madhur Rampal
Madhur Rampal

Reputation: 23

How to print list of dict in django?

I have list of dict named menu_dict_list:

[{'date': datetime.datetime(2011, 8, 15, 0, 0), 
  'Popcorn': 5, 'Coke': 5, 'Chips': 0, 'Burger': 3}, 
 {'date': datetime.datetime(2011, 8, 10, 0, 0), 
  'Popcorn': 4, 'Coke': 4, 'Chips': 0, 'Burger': 0}]

I had followed this approach:

**{% for menu_dict in menu_dict_list %}
 <tr> 
 {% for key,value in menu_dict %}
 <td>{{value}}</td>
 {% endfor %}
 </tr>
 {% endfor %}**

How to print it in django? But its not working good. Thanks in advance

Upvotes: 2

Views: 3621

Answers (2)

Uku Loskit
Uku Loskit

Reputation: 42040

You have to use the .items method of the dict:

{% for menu_dict in menu_dict_list %}
        <tr>
                {% for key,value in menu_dict.items %}
                        <td>{{value}}</td>
                {% endfor %}
        </tr>
{% endfor %}

See this

Upvotes: 2

christophe31
christophe31

Reputation: 6467

if your problem is to iterate on the dictionary, look here:

<ul>
{% for key,value in menu_dict.iteritems %}
    <li><b>{{ key }}:</b> {{ value }} </li>
{% endfor %}
</ul>

And just in case you want to make a beautiful table with this, note that dictionary are not ordered so, you may want to use django SortedDict or a list of list of 2entries tuples.

Upvotes: 1

Related Questions