Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 s.course. So my problem is I need to double-substitute this variable. I don't want to use a for 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 s.course values could change so obviously hard-coding them like this is bad. I want it to work essentially like this:

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

But I want it to look like this:

{{course_codes.{{s.course}}}} 

Thanks!

like image 732
tytk Avatar asked Sep 16 '13 14:09

tytk


People also ask

Can a dictionary value be a variable?

You can assign a dictionary value to a variable in Python using the access operator [].

How do you iterate through a dictionary in Jinja?

To iterate through a list of dictionaries in Jinja template with Python Flask, we use a for loop. to create the parent_list list of dicts. in our Jinja2 template to render the parent_list items in a for loop.

What method can you use to retrieve a value from a dictionary by using the key?

You can use the get() method of the dictionary ( dict ) to get any default value without an error if the key does not exist. Specify the key as the first argument. The corresponding value is returned if the key exists, and None is returned if the key does not exist.

How do you get all the keys values from a dict?

In Python to get all values from a dictionary, we can use the values() method. The values() method is a built-in function in Python and returns a view object that represents a list of dictionaries that contains all the values.


2 Answers

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() u'123' 
like image 144
R. Max Avatar answered Sep 20 '22 19:09

R. Max


There is no need to use the dot notation at all, you can do:

"{{course_codes[s.course]}}" 
like image 21
Mike Vella Avatar answered Sep 20 '22 19:09

Mike Vella