1

I'm trying to read a dictionary in a template in Django, but I would like to separate the keys and the values. The key is what will be showed, and the value is the next url it has to go (I know that the dictionary is a little bit strange but I think that's not a problem).

Here is my code if anyone can help me?

<ul> 
    {% for i in respuestas %}
        <li><a href="/{{'respuestas.[i]'}}"><h2>{{i}}</h2></a></li>
    {% endfor %}
</ul>

That's the idea. Obviously it doesn't work because I'm asking here so, anyone know how can I do it??

Thank you!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Gonsa02
  • 333
  • 3
  • 13
  • Does this answer your question? [How to access a dictionary element in a Django template?](https://stackoverflow.com/questions/1275735/how-to-access-a-dictionary-element-in-a-django-template) – trdwll Apr 25 '20 at 15:24
  • what output(HTML) do you get for your code here ? – Ansuman Apr 25 '20 at 15:47
  • Does this answer your question? [how to iterate through dictionary in a dictionary in django template?](https://stackoverflow.com/questions/8018973/how-to-iterate-through-dictionary-in-a-dictionary-in-django-template) – iklinac Apr 25 '20 at 16:45

2 Answers2

0

to separate the keys and the value, this works fine

>>> dict = {'name':'sirus', 'age':34, 'role':'godfather'}
>>> for i in dict:
...     print(i, dict[i])
('age', 34)
('role', 'godfather')
('name', 'sirus')

so your template code would look something like this.

<ul> 
    {% for i in respuestas %}
        <li><a href="{{respuestas[i]}}"><h2>{{i}}</h2></a></li>
    {% endfor %}
</ul>
Ansuman
  • 428
  • 1
  • 4
  • 15
0
<ul> 
{% for key, value in respuestas.items %}
    <li><a href="/{{ value }}"><h2>{{ key }}</h2></a></li>
{% endfor %}
</ul>

This works for me.

bertinhogago
  • 339
  • 2
  • 6