Access Dictionary Elements in Django Templates with Python

In this tutorial, we will learn 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.

Code Example:

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.

#python 

1.55 GEEK