Last updated: Apr 11, 2024
Reading timeยท5 min
To iterate over a list of dictionaries in a Jinja template:
template.render()
.for
loop to iterate over the list.for
loop to iterate over the dictionary's items in the Jinja
template.Here is the code for the main.py
file.
from jinja2 import Environment, FileSystemLoader employee_list = [ {"id": 1, "name": "Alice", "age": 30}, {"id": 2, "name": "Bobby", "age": 40}, {"id": 3, "name": "Carl", "age": 50}, ] environment = Environment(loader=FileSystemLoader("templates/")) template = environment.get_template("home.html") # ๐๏ธ pass the list of dictionaries as a variable to the template content = template.render(employee_list=employee_list) print(content)
And here is the code for the templates/home.html
file.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div>bobbyhadz.com</div> {% for dict_item in employee_list %} {% for key, value in dict_item.items() %} <h1>Key: {{key}}</h1> <h2>Value: {{value}}</h2> {% endfor %} {% endfor %} </body> </html>
The code sample assumes that you have the following folder structure.
my-project/ โโโ main.py โโโ templates/ โโโ home.html
Now, I'll run the main.py
file with python main.py
to look at the output.
python main.py # ๐๏ธ or with python3 python3 main.py
Here is a part of the produced template:
<h1>Key: id</h1> <h2>Value: 1</h2> <h1>Key: name</h1> <h2>Value: Alice</h2> <h1>Key: age</h1> <h2>Value: 30</h2> <h1>Key: id</h1> <h2>Value: 2</h2> <h1>Key: name</h1> <h2>Value: Bobby</h2> <h1>Key: age</h1> <h2>Value: 40</h2>
There are two main steps for iterating over a list of dictionaries in a Jinja template:
template.render()
method.# ... employee_list = [ {"id": 1, "name": "Alice", "age": 30}, {"id": 2, "name": "Bobby", "age": 40}, {"id": 3, "name": "Carl", "age": 50}, ] # ... # ๐๏ธ pass the list as a variable to the template content = template.render(employee_list=employee_list)
for
loop in the Jinja template.{% for dict_item in employee_list %} {% for key, value in dict_item.items() %} <h1>Key: {{key}}</h1> <h2>Value: {{value}}</h2> {% endfor %} {% endfor %}
The first for
loop iterates over the employee_list
variable.
The nested for
loop uses the
dict.items() method
to iterate over each dictionary.
The dict.items()
method returns a new view of the dictionary's items ((key,
value) pairs).
employee_list = [ {"id": 1, "name": "Alice", "age": 30}, {"id": 2, "name": "Bobby", "age": 40}, {"id": 3, "name": "Carl", "age": 50}, ] # ๐๏ธ dict_items([('id', 1), ('name', 'Alice'), ('age', 30)]) print(employee_list[0].items())
On each iteration, we render the current dictionary key and value.
Here is an example of manually accessing the keys of each dictionary in the Jinja template.
The folder structure for the project remains the same.
my-project/ โโโ main.py โโโ templates/ โโโ home.html
Here is the code for the main.py
file.
from jinja2 import Environment, FileSystemLoader employee_list = [ {"id": 1, "name": "Alice", "age": 30}, {"id": 2, "name": "Bobby", "age": 40}, {"id": 3, "name": "Carl", "age": 50}, ] environment = Environment(loader=FileSystemLoader("templates/")) template = environment.get_template("home.html") content = template.render(employee_list=employee_list) print(content)
And here is the code for the templates/home.html
file.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div>bobbyhadz.com</div> {% for dict_item in employee_list %} <h2>ID: {{dict_item['id']}}</h2> <h2>Name: {{dict_item['name']}}</h2> <h2>Age: {{dict_item['age']}}</h2> {% endfor %} </body> </html>
Running my Python script with python main.py
produces the following output.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div>bobbyhadz.com</div> <h2>ID: 1</h2> <h2>Name: Alice</h2> <h2>Age: 30</h2> <h2>ID: 2</h2> <h2>Name: Bobby</h2> <h2>Age: 40</h2> <h2>ID: 3</h2> <h2>Name: Carl</h2> <h2>Age: 50</h2> </body> </html>
Here is the related code in the Jinja template.
{% for dict_item in employee_list %} <h2>ID: {{dict_item['id']}}</h2> <h2>Name: {{dict_item['name']}}</h2> <h2>Age: {{dict_item['age']}}</h2> {% endfor %}
We used a for
loop to iterate over the list of dictionaries.
On each iteration, we use square brackets to access a dictionary key.
The same syntax is used when you need to access a key in a plain dictionary.
Let's look at an example of iterating over a dictionary in a Jinja template.
The folder structure for the project remains the same.
my-project/ โโโ main.py โโโ templates/ โโโ home.html
Here is the code for the main.py
file.
from jinja2 import Environment, FileSystemLoader employee_dict = { 'id': 1, 'name': 'Bobby Hadz', 'age': 30, } environment = Environment(loader=FileSystemLoader("templates/")) template = environment.get_template("home.html") content = template.render(employee_dict=employee_dict) print(content)
And here is the code for the templates/home.html
file.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div>bobbyhadz.com</div> {% for key, value in employee_dict.items() %} <h1>Key: {{key}}</h1> <h2>Value: {{value}}</h2> {% endfor %} </body> </html>
Running the Python script with python main.py
produces the following output.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div>bobbyhadz.com</div> <h1>Key: id</h1> <h2>Value: 1</h2> <h1>Key: name</h1> <h2>Value: Bobby Hadz</h2> <h1>Key: age</h1> <h2>Value: 30</h2> </body> </html>
# ... employee_dict = { 'id': 1, 'name': 'Bobby Hadz', 'age': 30, } # ... content = template.render(employee_dict=employee_dict)
dict.items()
.{% for key, value in employee_dict.items() %} <h1>Key: {{key}}</h1> <h2>Value: {{value}}</h2> {% endfor %}
The for
loop iterates over the dictionary's items.
On each iteration, we display the current key and value.
The following example shows how to access dictionary keys in a Jinja template.
The dictionary key might or might not be stored in a variable.
The folder structure for the project remains the same.
my-project/ โโโ main.py โโโ templates/ โโโ home.html
Here is the code for the main.py
file.
from jinja2 import Environment, FileSystemLoader employee_dict = { 'id': 1, 'name': 'Bobby Hadz', 'age': 30, } environment = Environment(loader=FileSystemLoader("templates/")) template = environment.get_template("home.html") content = template.render( employee_dict=employee_dict, name_key='name' ) print(content)
And, here is the code for the templates/home.html
file.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div>bobbyhadz.com</div> <h2>ID: {{employee_dict['id']}}</h2> <h2>Name: {{employee_dict.get(name_key)}}</h2> <h2>Name: {{employee_dict[name_key]}}</h2> <h2>Age: {{employee_dict['age']}}</h2> </body> </html>
Running the Python script with python main.py
produces the following output.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div>bobbyhadz.com</div> <h2>ID: 1</h2> <h2>Name: Bobby Hadz</h2> <h2>Name: Bobby Hadz</h2> <h2>Age: 30</h2> </body> </html>
template.render()
.# ... employee_dict = { 'id': 1, 'name': 'Bobby Hadz', 'age': 30, } # ... content = template.render( employee_dict=employee_dict, name_key='name' )
Here is the code in the Jinja template that accesses the dictionary keys.
<h2>ID: {{employee_dict['id']}}</h2> <h2>Name: {{employee_dict.get(name_key)}}</h2> <h2>Name: {{employee_dict[name_key]}}</h2> <h2>Age: {{employee_dict['age']}}</h2>
We used bracket notation to get the values of the id
and age
keys.
The name
key is stored in a variable that was also passed to the Jinja
template.
The first example uses the dict.get()
method to get the value of the name
key.
The second example uses bracket notation to get the value of the name
key.
The dict.get method returns the value for the given key if the key is in the dictionary, otherwise a default value is returned.
The method takes the following 2 parameters:
Name | Description |
---|---|
key | The key for which to return the value |
default | The default value to be returned if the provided key is not present in the dictionary (optional) |
Here is an example of providing a default value that is returned when the key doesn't exist in the dictionary.
<h2>Name: {{employee_dict.get('another_key', 'default value')}}</h2>
Running python main.py
produces the following output.
<h2>Name: default value</h2>
The specified key doesn't exist in the dictionary, so the default value is returned.
If a value for the default
parameter is not provided, it defaults to None
,
so the get()
method never raises a KeyError
.
You can learn more about the related topics by checking out the following tutorials: