Iterate Dictionary or List of dictionaries in Jinja template

avatar
Borislav Hadzhiev

Last updated: Apr 11, 2024
5 min

banner

# Table of Contents

  1. Iterating over a list of dictionaries in a Jinja template
  2. Manually accessing the keys of each dictionary in the Jinja template
  3. Iterating over a Dictionary in a Jinja template
  4. How to access dictionary keys in a Jinja template

# Iterating over a list of dictionaries in a Jinja template

To iterate over a list of dictionaries in a Jinja template:

  1. Pass the list of dictionaries as a variable in the call to template.render().
  2. Use a for loop to iterate over the list.
  3. Use a nested for loop to iterate over the dictionary's items in the Jinja template.

Here is the code for the main.py file.

main.py
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)
The code for this article is available on GitHub

And here is the code for the templates/home.html file.

templates/home.html
<!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.

shell
my-project/ โ””โ”€โ”€ main.py โ””โ”€โ”€ templates/ โ””โ”€โ”€ home.html

Now, I'll run the main.py file with python main.py to look at the output.

shell
python main.py # ๐Ÿ‘‡๏ธ or with python3 python3 main.py

iterate over list of dictionaries in jinja

Here is a part of the produced template:

templates/home.html
<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:

  1. Pass the list of dictionaries as a variable to the template.render() method.
main.py
# ... 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)
  1. Iterate over the list and then over each dictionary in the list with a nested for loop in the Jinja template.
templates/home.html
{% for dict_item in employee_list %} {% for key, value in dict_item.items() %} <h1>Key: {{key}}</h1> <h2>Value: {{value}}</h2> {% endfor %} {% endfor %}
The code for this article is available on GitHub

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).

main.py
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.

# Manually accessing the keys of each dictionary in the Jinja template

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.

shell
my-project/ โ””โ”€โ”€ main.py โ””โ”€โ”€ templates/ โ””โ”€โ”€ home.html

Here is the code for the main.py file.

main.py
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.

templates/home.html
<!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>
The code for this article is available on GitHub

Running my Python script with python main.py produces the following output.

templates/home.html
<!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>

manually accessing dictionary keys in jinja template

Here is the related code in the Jinja template.

templates/home.html
{% 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.

# Iterating over a Dictionary in a Jinja template

Let's look at an example of iterating over a dictionary in a Jinja template.

The folder structure for the project remains the same.

shell
my-project/ โ””โ”€โ”€ main.py โ””โ”€โ”€ templates/ โ””โ”€โ”€ home.html

Here is the code for the main.py file.

main.py
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)
The code for this article is available on GitHub

And here is the code for the templates/home.html file.

templates/home.html
<!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.

templates/home.html
<!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>

iterating over dictionary in jinja template

The code for this article is available on GitHub
  1. We first have to pass the dictionary as a variable to the Jinja template.
main.py
# ... employee_dict = { 'id': 1, 'name': 'Bobby Hadz', 'age': 30, } # ... content = template.render(employee_dict=employee_dict)
  1. Then we can iterate over the dictionary in the template with dict.items().
templates/home.html
{% 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.

# How to access dictionary keys in a Jinja template

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.

shell
my-project/ โ””โ”€โ”€ main.py โ””โ”€โ”€ templates/ โ””โ”€โ”€ home.html

Here is the code for the main.py file.

main.py
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)
The code for this article is available on GitHub

And, here is the code for the templates/home.html file.

templates/home.html
<!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.

templates/home.html
<!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>

accessing dictionary keys in jinja template

  1. We passed 2 variables when calling template.render().
main.py
# ... 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.

templates/home.html
<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:

NameDescription
keyThe key for which to return the value
defaultThe 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.

templates/home.html
<h2>Name: {{employee_dict.get('another_key', 'default value')}}</h2>

Running python main.py produces the following output.

templates/home.html
<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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev