1

My question is if there's a way to obtain a value of a dictionary given a key. For example, imagine that my_dictionary is {1:'a', 2:'b', 3:'c'}and I have an attribute which is key which equals 1. How can I obtain 'a'? I tried with {{my_dictionary.key}}and {{my_dictionary.{{key}} }}but none of them worked. My idea is to do the same as with python, which is my_dictionary[key] but in a Django Template.

Thank you

josembell
  • 29
  • 4

2 Answers2

0

You can achieve this by:

{% for key, values in data.items %}
   {% if key == 1 %}
      {{ value }}
   {% endif %}
{% endfor %}
ruddra
  • 50,746
  • 7
  • 78
  • 101
0

The best way to approach this is to write a custom template filter:

from django.template.defaulttags import register
register = Library()
...
@register.filter
def get_item(dictionary, key):
    # use .get so that if the key does not exist a KeyError will be raised
    return dictionary.get(key)

usage in templates:

{{ data.items|get_item:<key_variable_here> }}