Categories
Python Answers

How to access a dictionary element in a Django template with Python?

Spread the love

Sometimes, we want to access a dictionary element in a Django template with Python.

In this article, we’ll look at how to access a dictionary element in a Django template with Python.

How to access a dictionary element in a Django template with Python?

To access a dictionary element in a Django template with Python, we can use the items property to get the key-value pairs.

For instance, if we have

choices = {'key1':'val1', 'key2':'val2'}

Then we can render the key-value pairs in the template with

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

We get the key-value pairs with choices.items.

And then we render the values with the for loop.

Conclusion

To access a dictionary element in a Django template with Python, we can use the items property to get the key-value pairs.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *