[python] How to iterate through a list of dictionaries in Jinja template?

I tried:

list1 = [{"username": "abhi", "pass": 2087}]
return render_template("file_output.html", list1=list1)

In the template:

<table border=2>
  <tr>
    <td>
      Key
    </td>
    <td>
      Value
    </td>
  </tr>
  {% for dictionary in list1 %}
    {% for key in dictionary %}
      <tr>
        <td>
          <h3>{{ key }}</h3>
        </td>
        <td>
          <h3>{{ dictionary[key] }}</h3>
        </td>
      </tr>
    {% endfor %}
  {% endfor %}
</table>

The above code is splitting each element into multiple characters:

[

{

"

u

s

e

r

...

I tested the above nested loop in a simple Python script and it works fine but not in Jinja template.

This question is related to python dictionary flask iteration jinja2

The answer is


{% for i in yourlist %}
  {% for k,v in i.items() %}
    {# do what you want here #}
  {% endfor %}
{% endfor %}

Just a side note for similar problem (If we don't want to loop through):

How to lookup a dictionary using a variable key within Jinja template?

Here is an example:

{% set key = target_db.Schema.upper()+"__"+target_db.TableName.upper() %}
{{ dict_containing_df.get(key).to_html() | safe }}

It might be obvious. But we don't need curly braces within curly braces. Straight python syntax works. (I am posting because I was confusing to me...)

Alternatively, you can simply do

{{dict[target_db.Schema.upper()+"__"+target_db.TableName.upper()]).to_html() | safe }}

But it will spit an error when no key is found. So better to use get in Jinja.


As a sidenote to @Navaneethan 's answer, Jinja2 is able to do "regular" item selections for the list and the dictionary, given we know the key of the dictionary, or the locations of items in the list.

Data:

parent_dict = [{'A':'val1','B':'val2', 'content': [["1.1", "2.2"]]},{'A':'val3','B':'val4', 'content': [["3.3", "4.4"]]}]

in Jinja2 iteration:

{% for dict_item in parent_dict %}
   This example has {{dict_item['A']}} and {{dict_item['B']}}:
       with the content --
       {% for item in dict_item['content'] %}{{item[0]}} and {{item[1]}}{% endfor %}.
{% endfor %}

The rendered output:

This example has val1 and val2:
    with the content --
    1.1 and 2.2.

This example has val3 and val4:
   with the content --
   3.3 and 4.4.

**get id from dic value. I got the result.try the below code**
get_abstracts = s.get_abstracts(session_id)
    sessions = get_abstracts['sessions']
    abs = {}
    for a in get_abstracts['abstracts']:
        a_session_id = a['session_id']
        abs.setdefault(a_session_id,[]).append(a)
    authors = {}
    # print('authors')
    # print(get_abstracts['authors'])
    for au in get_abstracts['authors']: 
        # print(au)
        au_abs_id = au['abs_id']
        authors.setdefault(au_abs_id,[]).append(au)
 **In jinja template**
{% for s in sessions %}
          <h4><u>Session : {{ s.session_title}} - Hall : {{ s.session_hall}}</u></h4> 
            {% for a in abs[s.session_id] %}
            <hr>
                      <p><b>Chief Author :</b>  Dr. {{ a.full_name }}</p>  
               
                {% for au in authors[a.abs_id] %}
                      <p><b> {{ au.role }} :</b> Dr.{{ au.full_name }}</p>
                {% endfor %}
            {% endfor %}
        {% endfor %}

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to dictionary

JS map return object python JSON object must be str, bytes or bytearray, not 'dict Python update a key in dict if it doesn't exist How to update the value of a key in a dictionary in Python? How to map an array of objects in React C# Dictionary get item by index Are dictionaries ordered in Python 3.6+? Split / Explode a column of dictionaries into separate columns with pandas Writing a dictionary to a text file? enumerate() for dictionary in python

Examples related to flask

Flask at first run: Do not use the development server in a production environment Flask - Calling python function on button OnClick event python-How to set global variables in Flask? In Flask, What is request.args and how is it used? How to print from Flask @app.route to python console What does "app.run(host='0.0.0.0') " mean in Flask Making an asynchronous task in Flask Flask ImportError: No Module Named Flask can you add HTTPS functionality to a python flask web server? How to get http headers in flask?

Examples related to iteration

Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply? How to loop over grouped Pandas dataframe? How to iterate through a list of dictionaries in Jinja template? How to iterate through an ArrayList of Objects of ArrayList of Objects? Ways to iterate over a list in Java Python list iterator behavior and next(iterator) How to loop through an array containing objects and access their properties recursion versus iteration What is the perfect counterpart in Python for "while not EOF" How to iterate over a JavaScript object?

Examples related to jinja2

'if' statement in jinja2 template Ansible: filter a list by its attributes Split string into list in jinja? How to iterate through a list of dictionaries in Jinja template? How to write dynamic variable in Ansible playbook Jinja2 template not rendering if-elif-else statement properly Jinja2 template variable if None Object set a default value Convert integer to string Jinja Link to Flask static files with url_for How to pass a list from Python, by Jinja2 to JavaScript