Explain Codes LogoExplain Codes Logo

Django template how to look up a dictionary value with a variable

python
django-templates
custom-filters
advanced-django
Alex KataevbyAlex Kataev·Feb 5, 2025
TLDR

The key to access a dynamic key in a Django template is by creating a custom template filter. We can name it get_item for this case.

Here's how you can do this:

  1. Define the filter in templatetags/custom_filters.py:
from django.template.defaulttags import register @register.filter def get_item(dictionary, key): # No KeyError today! return dictionary.get(key, 'Sorry, no value found!')
  1. Load the filter and use it inside your template:
{% load custom_filters %} {{ my_dict|get_item:dynamic_key }}

Now it will evaluate dynamic_key and retrieve the related value from my_dict.

More than just getting an item

Above we have seen how we can easily get an item from dictionary using custom filter. But Django provides much more. Let’s dive deeper and understand.

Digging deep with nested dictionaries

Got a nested dictionary? No problem, our get_item filter can be extended to dig deeper.

@register.filter def get_nested_item(dictionary, key): keys = key.split('.') value = dictionary for key in keys: value = value.get(key, None) # None shall pass if key doesn't exist! if value is None: break return value

To use it:

{{ my_dict|get_nested_item:"parent_key.child_key" }}

Looping with keys from variables

Using loop variables as keys? The get_item filter comes to the rescue.

{% for item in listOfKeys %} {{ my_dict|get_item:item.NAME }} {% endfor %}

Custom filter best practices

Here are some tips when creating your filters:

  • Define them in a templatetags subdirectory within your app.
  • Add error handling to return a fallback value when necessary.
  • Include docstrings and comments for maintenance.
  • Test your filters, especially when dealing with complex data structures.

Advanced Django template practices

Looping over dictionaries

To iterate over a dictionary within a template:

{% for key, value in my_dict.items %} - {{ key }}: {{ value }} {% endfor %}

Broadening horizons with advanced filters

For more complex operations, create advanced custom filters.

@register.filter def filter_for_complex_logic(value, arg): # Here we can put some really cool mechanics... return result

Walking with Django versions

When writing custom filters, keep in step with your Django version. Django's API can change, so always check the official documentation.