Accessing dictionary by key in Django template

I’m passing a dictionary from my view to a template. So {"key1":"value1","key2":"value2"} is passed in and looping through key,value pairs is fine, however I’ve not found an elegant solution from access directly in the view from a specific key, say "key1" for example bu json.items[“key1”]. I could use some if/then statements, but I’d rather do directly is there a way?

Here is looping code in the html template:

{% for key, value in json.items %} 
  <li>{{key}} - {{value}}</li>
 {% endfor %}

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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.

Solution 2

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

from django.template.defaultfilters import register

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 %}

Solution 3

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

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

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

It prints 'myname'

Solution 4

To overcome this problem you could try something like this:

def get_context_data(self, **kwargs):
    context['cart'] = []
    cart = Cart() = =
    cart.publisher =
    cart.price = 123 = 12 = 100
    return context

class Cart(object):
    Cart Template class

    This is a magic class, having attributes
    name, author, publisher, price, discount, total, image
    You can add other attributes on the fly

By this way you can access your cart something like this:
{% for item in cart %}
    <div class="jumbotron">
    <img src="{{item.image}}" />
    <div class="book_name"> <b>{{}}</b></div>
    <div class="book_by"><i>{{}}</i></div>
    <span>Rs. {{item.price}}</span> <i>{{}}% OFF </i>
    <b>Rs. {{}}</b>
{% endfor %}

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply