134

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.

ivanleoncz
  • 9,070
  • 7
  • 57
  • 49
user3089927
  • 3,575
  • 8
  • 25
  • 33

5 Answers5

276

Data:

parent_list = [{'A': 'val1', 'B': 'val2'}, {'C': 'val3', 'D': 'val4'}]

in Jinja2 iteration:

{% for dict_item in parent_list %}
   {% for key, value in dict_item.items() %}
      <h1>Key: {{key}}</h1>
      <h2>Value: {{value}}</h2>
   {% endfor %}
{% endfor %}

Note:

Make sure you have the list of dict items. If you get UnicodeError may be the value inside the dict contains unicode format. That issue can be solved in your views.py. If the dict is unicode object, you have to encode into utf-8.

Nuno André
  • 4,739
  • 1
  • 33
  • 46
Nava
  • 6,276
  • 6
  • 44
  • 68
  • 31
    Might be because I'm using a newer version of jinja, but in my case I had to remove the parentheses (use `dict_item.items` instead) or it would throw a `Could not parse the remainder: '()' from 'dict_item.items()'` – TrakJohnson Apr 05 '17 at 11:13
  • 2
    In addition to TrakJohnson's answer I have found that the new jinja indexes dicitonaries with `dict.key` instead of the conventional `dict["key"]`. – Cameron Hyde Feb 21 '19 at 06:43
  • 7
    @TrakJohnson: then you are **not using Jinja templating**, but are instead using *Django* templates. You want to read [how to iterate through dictionary in a dictionary in django template?](//stackoverflow.com/q/8018973). Django template syntax is similar, but not the same. – Martijn Pieters Apr 24 '19 at 13:20
  • 5
    @CameronHyde: Jinja, in all versions, supports both attribute and item access on all objects. See the [*Variables* section of the template documentation](http://jinja.pocoo.org/docs/2.10/templates/#variables). If `dict["key"]` doesn't work for you, then you are not using Jinja templates, but Django templates. See [Accessing dictionary by key in Django template](//stackoverflow.com/q/19745091) – Martijn Pieters Apr 24 '19 at 13:22
  • 1
    what if you want to use each item in the dictionary in a different way - you don't want to loop through the keys but you still want to access the keys? – MetaStack Jun 27 '19 at 21:37
28

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.
Community
  • 1
  • 1
Chris.Q
  • 1,370
  • 16
  • 21
18
{% for i in yourlist %}
  {% for k,v in i.items() %}
    {# do what you want here #}
  {% endfor %}
{% endfor %}
corvid
  • 10,733
  • 11
  • 61
  • 130
  • 1
    {% for k,v in lis1.items() %} UndefinedError: 'unicode object' has no attribute 'items' – user3089927 Aug 18 '14 at 22:55
  • 2
    @user3089927 is there more to your template than you're showing us? This solution is correct. If it's not, `lis` is not a list when the code you've shared is executed. – dirn Aug 19 '14 at 15:32
  • I overlooked a thing. I had to replace double quotes in a list dictionary and when I do it, it obviously converts the list of dictionary into string. I will post other ques with the problem I am facing. – user3089927 Aug 19 '14 at 19:26
0

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.

otterb
  • 2,660
  • 2
  • 29
  • 48
0
**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 %}