Django ValueError: Need 3 values to unpack in for loop; got 2. How to unpack zipped data in template?

Viewed 225

I was trying to display some zipped data in a table within a Django template and kept getting this error: ValueError: Need 3 values to unpack in for loop; got 2. It contains a dictionary and a list. I've tested the same code in idle and it prints out fine. What am I doing wrong? Thanks in advance!


Here's what i did for Django:

views.py

labels = [1, 4, 5]
mydic = {'a': ['a','b','c'], 'b':['e','f','g'], 'c':['l','m','n']}
dic_items = mydic.items()

zipped = zip(dic_items, labels)

base.html

    <table>
        {% for (k, v), l in zipped %}
        <tr>
            <th>Label{{ l }}</th>
            <td>{{ v.0 }}</td>
            <td>{{ v.1 }}</td>
            <td>{{ v.2 }}</td>
        </tr> 
        {% endfor %}
    </table>

In idle with the same code it prints out:

a
['a', 'b', 'c']
1
b
['e', 'f', 'g']
4
c
['l', 'm', 'n']
5

I've also tried:

{% for k, v, l in zipped %};
{% for k, v in dic_items %}{% for l in labels %};
{% for k,v in dic_items, for l in labels %}, etc.

None of them worked.

I suspect it might have something to do with the label doesn't contain the same amount of items as v? But it is the same amount as the keys in the dictionary. So my goal is to have a label for each line, ideally to look like this:

Label 1 | a | b | c

Label 4 | e | f | g

Label 5 | l | m | n

Is there a way to do this?

1 Answers

Tha parenthesis are likely the problem. You can use subscripting to access the key and values:

<table>
    {% for kv, l in zipped %}
    <tr>
        <th>Label{{ l }}</th>
        <td>{{ kv.1.0 }}</td>
        <td>{{ kv.1.1 }}</td>
        <td>{{ kv.1.2 }}</td>
    </tr> 
    {% endfor %}
</table>

That being said, in earlier versions of Python, a dictionary provided data in an "unpredictable" order. So in that case, it does not make much sense to zip(…) with the items of a dictionary since the order can each time be different.

Related