Accessing a dict by variable in Django templates?


Question

My view code looks basically like this:

context = Context() 
context['my_dict'] = {'a': 4, 'b': 8, 'c': 15, 'd': 16, 'e': 23, 'f': 42 }
context['my_list'] = ['d', 'f', 'e', 'b', 'c', 'a']

And what I'd like to do in my Django template is this:

<ul>
{% for item in my_list %} 
  <li>{{ item }} : {{ my_dict.item }}</li>
{% endfor %} 
</ul>

And I'd like this to output:

<ul> 
  <li> d : 16 </li> 
  <li> f : 42 </li> 
  <li> e : 23 </li> 
  <li> b : 8 </li> 
  <li> c : 15 </li> 
  <li> a : 4 </li> 
</ul> 

But the reference to the dict by variable name via {{ my_dict.item }} doesn't actually work. I suspect it's internally doing my_dict['item'] instead of my_dict[item]. Is there any way to work around this?

1
26
11/9/2012 3:09:01 AM

Accepted Answer

There's no builtin way to do that, you'd need to write a simple template filter to do this: http://code.djangoproject.com/ticket/3371

15
1/14/2010 7:48:43 PM

Try this to display the keys and values of the dictionary:

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

https://docs.djangoproject.com/en/dev/ref/templates/builtins/#for


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon