Accessing dictionary by key in Django template Accessing dictionary by key in Django template json json

Accessing dictionary by key in Django template


The Django template language supports looking up dictionary keys as follows:

{{ json.key1 }}

See the template docs on variables and lookups.

The template language does not provide a way to display json[key], where key is a variable. You can write a template filter to do this, as suggested in the answers to this Stack Overflow question.


As @Alasdair suggests, you can use a template filter. In your templatetags directory, create the following file dict_key.py:

from django.template.defaultfilters import register@register.filter(name='dict_key')def dict_key(d, k):    '''Returns the given key from a dictionary.'''    return d[k]

Then, in your HTML, you can write:

{% for k in json.items %}   <li>{{ k }} - {{ json.items|dict_key:k }}</li>{% endfor %}


For example, to send the below dictionarydict = {'name':'myname','number':'mynumber'}

views :return render(request, self.template_name, {'dict': dict})

To render the value in html template:<p>{{ dict.name }}</p>

It prints 'myname'