[Answered ]-How to iterate this dictionary of lists of lists in Django?

2👍

I’m not sure what args=dict(Qtag=Questag) means in your code (since I don’t know what Questag is). I don’t know whether your tags are iterable either (I’m assuming so). Your HTML looks malformed too (e.g. I don’t see an opening h4).

This is what I’d do to get something similar to what you’re looking for. You can work on this.

{% if Qtag %}
   {% for question, tags in Qtag %}
     {# First put in the question header #}
     <h4>Question : {{question.qid}} {{question.title}} </h4>
     {# Then the question body #}
     <p>
     {{question.question}}
     </p>
     {# Now a tag list #}
     <ul>
     {% for tag in tags %}
       <li> 
          <button name = "tag" type="submit" value="{{tag.name}}"> 
            {{tag.name}} 
          </button>
       </li>
     {% endfor %}      
     </ul>
   {% endfor %}
{% endif %}

Your original solution is iterating over the list quadratically (you’re iterating over the list once for every outer iteration) and that’s why you’re seeing things being printed 4 times.

Leave a comment