ChaChaPoly
ChaChaPoly

Reputation: 1851

Building HTML table from list of dictionaries

I have a list containing dictionaries that I would like to output into an HTML table.

My list looks like this:

[{'description': 'KA8ts5', 'password': 'KA8ts5', 'username': 'test4'}, 
 {'description': '5j6mEF', 'password': '5j6mEF', 'username': 'test5'}]

I am trying to make it look as follows:

<tr><td>test4</td><td>KA8ts5</td></tr>
<tr><td>test5</td><td>5j6mEF</td></tr>

But I am unsure how to get these values as well as format them accordingly.

Upvotes: 0

Views: 1436

Answers (2)

alecxe
alecxe

Reputation: 473863

I would use a template engine like mako or jinja2.

Example using mako:

from mako.template import Template

template = """
<table>
% for user in users:
     <tr>
        <td>${user['username']}</td>
        <td>${user['description']}</td>
     </tr>
% endfor
</table>
"""

users = [
    {'description': 'KA8ts5', 'password': 'KA8ts5', 'username': 'test4'},
    {'description': '5j6mEF', 'password': '5j6mEF', 'username': 'test5'}
]
result = Template(template).render(users=users)
print(result)

Prints:

<table>
     <tr>
        <td>test4</td>
        <td>KA8ts5</td>
     </tr>
     <tr>
        <td>test5</td>
        <td>5j6mEF</td>
     </tr>
</table>

Upvotes: 1

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160427

You could use an example supplied in the docs for contextlib and build it accordingly.

Essentially, create a context manager with @contextmanager that adds initial and closing tags and print out the required values in the with block. The context manager, as found in the docs:

from contextlib import contextmanager

@contextmanager
def tag(name):
    print("<%s>" % name, end='')
    yield
    print("</%s>" % name, end='')

and, the actual sample that uses it:

l = [{'description': 'KA8ts5', 'password': 'KA8ts5', 'username': 'test4'}, 
     {'description': '5j6mEF', 'password': '5j6mEF', 'username': 'test5'}]    

for d in l:
    with tag('tr'):
        with tag('td'):
            print(d['username'], end='')
        with tag('td'):
            print(d['password'], end='')
    print()

Outputs:

<tr><td>test4</td><td>KA8ts5</td></tr>
<tr><td>test5</td><td>5j6mEF</td></tr>

Upvotes: 0

Related Questions