0

I meet some problem while I try to use the element of list as the key of dict in Django.

My code is below:

list = ['a', 'b', 'c']
dict = {'a' : 1, 'b' : 2, 'c' : 3}

{% for element in list %}
  {% for key, value in dict %}
    {{ value.element }}
  {% endfor %}
{% endfor %}

The question is that there is no key named element in dict, so it won't show the correct value. The correct result should be 1, 2, 3.

How can I use element of list as the key of dict instead of using the specific key in Django.

Thank you.

Jimmy Lin
  • 1,481
  • 6
  • 27
  • 44

1 Answers1

0

A similar question is answered there. The solution uses a template filter.

Another way to achieve what you want is to use a condition on the value of key:

{% for element in list %}
  {% for key, value in dict %}
    {% if key == element %}{{ value.element }}{% endif %}
  {% endfor %}
{% endfor %}
Community
  • 1
  • 1
mimo
  • 2,469
  • 2
  • 28
  • 49
  • what's the difference with and without the if condition? – Jimmy Lin Sep 17 '14 at 07:15
  • I am not sure what you really want to achieve. The example I gave will print '123'. Without the if condition, it would print three times the dictionary values: '123123123' (or in another order, since dict objets are not ordered in Python). If you just want to get the value of the key 'a', remove the loop over the elements in list and replace "element" by "'a'" in my example. – mimo Sep 17 '14 at 09:25