[Django]-Accessing a dict element who's key begins with an @

3๐Ÿ‘

โœ…

A custom template tag is the only way to access dictionary keys with special characters. The answer to this question provides a good example.

For the lazy:

from django import template
register = template.Library()

@register.filter
def dictKeyLookup(the_dict, key):
    # Try to fetch from the dict, and if it's not found return an empty string.
    return the_dict.get(key, '')

Which you would use like so:

{% dictKeyLookup your_dict "@blarg!#$^&*" %}

As homework, you could also convert this into a simple filter, which would give you a syntax like:

{{ your_dict|getkey:"@blarg!@#$%" }}
๐Ÿ‘คEvan Brumley

Leave a comment