Sai A Sai A
Updated date Aug 17, 2023
In this blog, we will discover multiple techniques to convert Python dictionaries into HTML. Learn manual HTML generation, dynamic Jinja2 templating, and specialized libraries.

Introduction:

This blog explores the various techniques to convert dictionaries into HTML in Python, using step-by-step explanations and accompanied by code examples.

Method 1: Manual HTML Generation

The most fundamental approach involves manually crafting HTML code. This grants full control over HTML structure and styling. Consider a scenario where we have a dictionary representing information about books.

def dict_to_html_manual(data_dict):
    html = "<ul>"
    for key, value in data_dict.items():
        html += f"<li><strong>{key}:</strong> {value}</li>"
    html += "</ul>"
    return html

book_data = {
    "Title": "The Great Gatsby",
    "Author": "F. Scott Fitzgerald",
    "Year": 1925
}

html_output = dict_to_html_manual(book_data)
print(html_output)

Output:

<ul>
    <li><strong>Title:</strong> The Great Gatsby</li>
    <li><strong>Author:</strong> F. Scott Fitzgerald</li>
    <li><strong>Year:</strong> 1925</li>
</ul>

Method 2: Jinja2 Templating

Jinja2, a powerful templating engine, facilitates the separation of HTML structure from data. This enhances code maintainability and readability, making it a popular choice for dynamic HTML generation.

from jinja2 import Template

def dict_to_html_jinja(data_dict):
    template = Template("""
    <ul>
        {% for key, value in data.items() %}
        <li><strong>{{ key }}:</strong> {{ value }}</li>
        {% endfor %}
    </ul>
    """)
    return template.render(data=data_dict)

html_output = dict_to_html_jinja(book_data)
print(html_output)

Output:

<ul>
    <li><strong>Title:</strong> The Great Gatsby</li>
    <li><strong>Author:</strong> F. Scott Fitzgerald</li>
    <li><strong>Year:</strong> 1925</li>
</ul>

Method 3: HTML Generating Libraries

Python offers specialized libraries for HTML generation. One such library is htmlgen, which streamlines creating HTML content.

from htmlgen import UL, LI, Strong

def dict_to_html_htmlgen(data_dict):
    ul = UL()
    for key, value in data_dict.items():
        li = LI()
        li.append(Strong(key + ":"))
        li.append(" " + value)
        ul.append(li)
    return str(ul)

html_output = dict_to_html_htmlgen(book_data)
print(html_output)

Output:

<ul>
    <li><strong>Title:</strong> The Great Gatsby</li>
    <li><strong>Author:</strong> F. Scott Fitzgerald</li>
    <li><strong>Year:</strong> 1925</li>
</ul>

Conclusion:

In this blog, we have learned how to convert dictionaries to HTML in  Python , we have covered three distinct methods. The manual approach offers fine-grained control, Jinja2 templating enables dynamic and clean code, while libraries like htmlgen provide high-level interfaces.

Comments (0)

There are no comments. Be the first to comment!!!