Please don't. Arbitrary dictionary lookups have not been implemented by Django, but for good reasons.
The main reason not to do this, is that logic in the template that needs this, is often business logic. Such logic does not belong to the template, but should be moved to the view.
Another problem is that Django's template engine is not very efficient: it requires a lot of context resolutions, and rendering logic, meaning that such dictionary lookups are thus not "for free", these will slow down rendering, especially if it is done in a loop.
Often it will also require resolving the variable that is the key, and this can make debugging more tricky, since it is possible that the result of the context resolution is not what one would expect. For example if the variable is not found, it will use the string_if_invalid
value [Django-doc], which is not per se what one might intend, and thus the behavior could produce a result, but a wrong result.
Finally if an error occurs, it makes debugging harder, and if something goes wrong, it is possible that this is passed silently, whereas it is often better that in case something fails, it is at least logged somewhere.
If you need to perform arbitrary subscripting or attribute lookups, that means you should move the logic from the template to the view. Indeed, in that case you prepare the data in the view, for example here with:
def my_view(request):
my_list = ['key2']
my_dict = {'key1': 'value1', 'key2': 'value2'}
result = [my_dict[k] for k in my_list]
return render(request, 'name-of-template.html', {'result': result})
and thus then process result
in the template, not the logic with my_dict
and my_list
.