python – Step through dictionary in template

Question:

I have the following view:

from django.shortcuts import render

def ini (request):
    dic = {"nombre" : "Mauro", "apellido" : "London", "sexo" : "M"}
    return render(request, "ini.html", dic )

and the ini.html:

{% extends 'base.html' %}
{% block content %}
 <body>
 <h1>Esto es una prueba {{ nombre }} {{ apellido }}</h1>
 <ul>
    {% for valor in dic %}
      <li>{{ dic[valor] }}</li>
    {% endfor %}
 </ul>
</body>
{% endblock %}

My question: I see that both the dictionary key "first name" and "last name" are printed if I refer directly to it … but I don't know how to print the dictionary by tracing from a for. I do it as it is done in python but it gives me an error.

I have tried with:

{% extends 'base.html' %}
{% block content %}
 <body>
 <h1>Esto es una prueba {{ nombre }} {{ apellido }}</h1>
 <ul>
    {% for key, value in dic.items %}
      <li>{{ key }} : {{ value }}</li>
    {% endfor %}
 </ul>
</body>
{% endblock %}

it does not give an error but it does not print anything …

Answer:

The dictionary keys that you pass to the render context argument in the view are the variables you can use in the template. In other words, when you do {% for key, value in dic.items %} 's like looking for the key "dic" in the dic dictionary passed to render .

What you can do is simply pass your dictionary as the value of a key of said dictionary:

view.py

from django.shortcuts import render

def ini(request):
    dic = {"nombre" : "Mauro", "apellido" : "London", "sexo" : "M"}
    return render(request, 'ini.html', context={"dic": dic})

ini.html

{% extends 'base.html' %}
{% block content %}
<body>
    <h1>Esto es una prueba {{ dic.nombre }} {{ dic.apellido }}</h1>
    <ul>
        {% for key, value in dic.items %}
        <li>{{ key }} : {{ value }}</li>
        {% endfor %}
    </ul>
</body>
{% endblock %}

With this you should get what you are looking for:

This is a test Mauro London

  • name: Mauro
  • Last name: London
  • gender: M

Scroll to Top