tytk tytk - 1 month ago 19x
Python Question

How to get values from dictionary in jinja when key is a variable?

I'm trying to retrieve entries from a python dictionary in jinja2, but the problem is I don't know what key I want to access ahead of time - the key is stored in a variable called

. So my problem is I need to double-substitute this variable. I don't want to use a
loop because that will go through the dictionary way more than is necessary. Here's a workaround that I created, but it's possible that the
values could change so obviously hard-coding them like this is bad. I want it to work essentially like this:

{% if s.course == "p11" %}
{% elif s.course == "m12a" %}
{% elif s.course == "m12b" %}
{% endif %}

But I want it to look like this:




You can use course_codes.get(s.course):

>>> import jinja2
>>> env = jinja2.Environment()
>>> t = env.from_string('{{ codes.get(mycode) }}')
>>> t.generate(codes={'a': '123'}, mycode='a').next()