How to access a dictionary element in a Django template?
you can use the dot notation:
Dot lookups can be summarized like this: when the template system encounters a dot in a variable name, it tries the following lookups, in this order:
- Dictionary lookup (e.g., foo["bar"])
- Attribute lookup (e.g., foo.bar)
- Method call (e.g., foo.bar())
- List-index lookup (e.g., foo[2])
The system uses the first lookup type that works. It’s short-circuit logic.
choices = {'key1':'val1', 'key2':'val2'}
Here's the template:
<ul>
{% for key, value in choices.items %}
<li>{{key}} - {{value}}</li>
{% endfor %}
</ul>
Basically, .items
is a Django keyword that splits a dictionary into a list of (key, value)
pairs, much like the Python method .items()
. This enables iteration over a dictionary in a Django template.