Iterating through Python dictionary with Jinja2

Question:

I’ve scoured the internet and can’t seem to find the solution that fits my case.

I have a dictionary:

{"1528430400000": 129, "1528516800000": 123.14, "1528603200000": 117.28, "1528689600000": 111.42, "1528776000000": 105.56, "1528862400000": 99.7, "1528948800000": 93.84, "1529035200000": 87.98, "1529121600000": 82.12, "1529208000000": 76.26, "1529294400000": 70.4, "1529380800000": 64.54, "1529467200000": 58.68, "1529553600000": 52.82, "1529640000000": 46.96, "1529726400000": 41.1, "1529812800000": 35.24, "1529899200000": 29.38, "1529985600000": 23.52, "1530072000000": 17.66, "1530158400000": 11.8, "1530244800000": 5.94, "1530331200000": 0.08, "1530417600000": 0}'

where each key is a javascript-formatted date.

I’m looking for a simple iteration through each key and value.

example:

{% for key,value in dict %}
{{key}}, {{value}}
{% endfor %}
Asked By: Alex Gonzalez

||

Answers:

You can pass dict.items to the template rendering object:

return flask.render_template('template_name', data = the_dict.items())

Then, in the HTML:

{%for a, b in data%}
  <span>Key: {{a}}, value: {{b}}</span>
{%endfor%}
Answered By: Ajax1234

Use:

{% for key, value in dict.items() %}
<h1>Key: {{key}}</h1>
<h2>Value: {{value}}</h2>
{% endfor %}
Answered By: Abhijeet Khangarot
{% if dict_var |type_debug == 'dict' %}
{% for key in dict_var   %}
      {{ key }}: "{{ dict_var[key] }}"
{% endfor %}
{% endif %}

use this will error: ValueError: too many values to unpack in sometimes

{% if dict_var |type_debug == 'dict' %}
{% for key, value in dict_var   %}
      {{ key }}: "{{ value }}"
{% endfor %}
{% endif %}
Answered By: 张馆长

let’s suppose your dictionary is "my_dict".

view.py (django) will have-

return render(request, ‘template’, { ‘my_dict’ :
my_dict })

HTML page will have-

{% for k,v in my_dict.items %}

{{ k }}: {{ v }} <br>

{% endfor %}

Answered By: Rohith
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.