Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary As Table In Django Template

I have a dictionary:

field = 

{
   u'Birthday:': [datetime.date(2012, 4, 6), datetime.date(2012, 4, 27)],
   u'Education': [u'A1', u'A2'],
   u'Job:': [u'job1', u'job2'],
   u'Child Sex:': [u'M', u'F']
}

My template code is:

<table width="100%" border="0">
     <tr>
        {% for k, v in field.items %}
            <th>{{ k }}</th>
        {% endfor %}
     </tr>
     <tr>
       {% for k,v in field.items %}
            <td>
                <table width="100%" border="0">
                 {% for a in v %}
                     <tr class="{% cycle 'odd' 'even' %}"><td>{{ a }}</td></tr>
                 {% endfor %}
                </table>
            </td>
        {% endfor %}
     </tr>
</table>

I want to show dictionary keys as table headers and esach value as row:

Birthday                          Education      Job        Child Sex
datetime.date(2012, 4, 6)         A1             job1       M
datetime.date(2012, 4, 27)        A2             job2       F

But I have to insert a second table. Is there any way toshow dictionary keys as table headers and esach value as rows?

Thanks in advance

like image 947
TheNone Avatar asked Apr 06 '12 06:04

TheNone


1 Answers

You can make the template code a lot easier to read if you provide the data as a table in your dictionary. It would look more like this:

field = {
    'headers': [u'Birthday:', u'Education', u'Job', u'Child Sex'],
    'rows': [[datetime.date(2012, 4, 6), u'A1', u'job1', u'M']
            ,[datetime.date(2012, 4, 27), u'A2', u'job2', u'F']]
}

You can now iterate over the headers as follows:

<tr>
{% for header in field.headers %}
    <th>{{ header }}</th>
{% endfor %}
</tr>

And each row can be displayed using:

<tr>    
{% for value in field.rows %}
    <td>{{ value }}</td>
{% endfor %}
</tr>

Now, you can obtain the 'headers' value using field.keys():

[u'Birthday:', u'Education', u'Job:', u'Child Sex:']

You can get the 'values' using the following loop (where 2 is the number of rows):

rows = []
for i in xrange(2):
    row = []
    for k in field.keys():
        row.append(field[k][i])
    rows.append(row)

Or as a one-liner:

rows = [[field[k][i] for k in field.keys()] for i in xrange(2)]
like image 145
Simeon Visser Avatar answered Sep 28 '22 08:09

Simeon Visser