views:

500

answers:

3

I have a dictionary

data = {'sok': [ [1, 10] ], 'sao': [ [1, 10] ],'sok&sao':[ [2,20]] }

How Can I (Loop trough Dictionary ) present My data as (HTML) table to Django template.?? This format that as table

 author       qty            Amount
 sok            1              10         
 sao            1              10         
 sok&sao        2              20
 total
+1  A: 

You can iterate through the dictionary items, and count the corresponding items in your lists.

qty,amount=0,0
for k, v in data.iteritems():
    qty += v[0]
    amount += v[1]

print qty
print amount
Josh Smeaton
not really,i want.(present in template)
python
The principle is the same.
Josh Smeaton
+9  A: 

You can use the dict.items() method to get the dictionary elements:

<table>
    <tr>
        <td>author</td>
        <td>qty</td>
        <td>Amount</td>
    </tr>

    {% for author, values in data.items %}
    <tr>
        <td>{{author}}</td>
        {% for v in values[0] %}
        <td>{{v}}</td>
        {% endfor %}
    </tr>
    {% endfor %}
</table>
notnoop
values[0] not working
python
+1  A: 

Unfortunately, django templates do not deal with Python tuples. So it is not legal to use "for author, values" in the template. Instead, you must access tuple or array values by their index by using ".index", as in "tuple.0" and "tuple.1".

<table>
    <tr>
        <td>author</td>
        <td>qty</td>
        <td>Amount</td>
    </tr>

    {% for entry in data.items %}
    <tr>
        <td>{{entry.0}}</td>
        {% for v in entry.1 %}
        <td>{{v}}</td>
        {% endfor %}
    </tr>
    {% endfor %}
</table>
Brian H