24

Is there any (existing) way to display a python dictionary as html table in an ipython notebook. Say I have a dictionary

d = {'a': 2, 'b': 3}

then i run

magic_ipython_function(d)

to give me something like

enter image description here

1

8 Answers 8

15

You can write a custom function to override the default _repr_html_ function.

class DictTable(dict):
    # Overridden dict class which takes a dict in the form {'a': 2, 'b': 3},
    # and renders an HTML Table in IPython Notebook.
    def _repr_html_(self):
        html = ["<table width=100%>"]
        for key, value in self.iteritems():
            html.append("<tr>")
            html.append("<td>{0}</td>".format(key))
            html.append("<td>{0}</td>".format(value))
            html.append("</tr>")
        html.append("</table>")
        return ''.join(html)

Then, use it like:

DictTable(d)

Output will be: Sample Output of DictTable

If you are going to handle much bigger data (thousands of items), consider going with pandas.

Source of idea: Blog post of ListTable

Sign up to request clarification or add additional context in comments.

2 Comments

Small adjustment for python 3: use for key, value in iter(self.items()): for the loop
Use html.escape(str(key)) and html.escape(str(value)) instead of key and value.
13

You're probably looking for something like ipy_table.

A different way would be to use pandas for a dataframe, but that might be an overkill.

1 Comment

Looks interesting, especially the possibility to style the tables.
11

I wouldn't say pandas is an overkill, as you might use the DataFrame as a dict, among other things.

Anyway, you can do:

pd.DataFrame.from_dict(d, orient="index")

or

pd.DataFrame(d.values(), index=d.keys())

Comments

6

Working Code: Tested in Python 2.7.9 and Python 3.3.5

In [1]:

from ipy_table import *

# dictionary
dict = {'a': 2, 'b': 3}

# lists
temp = []
dictList = []

# convert the dictionary to a list
for key, value in dict.iteritems():
    temp = [key,value]
    dictList.append(temp)

# create table with make_table
make_table(dictList)

# apply some styles to the table after it is created
set_column_style(0, width='100', bold=True, color='hsla(225, 80%, 94%, 1)')
set_column_style(1, width='100')

# render the table
render()

Out [1]:

table screenshot


Get the generated html:

In [2]:

render()._repr_html_()

Out [2]:

'<table border="1" cellpadding="3" cellspacing="0"  style="border:1px solid black;border-collapse:collapse;"><tr><td  style="background-color:hsla(225, 80%, 94%, 1);width:100px;"><b>a</b></td><td  style="width:100px;">2</td></tr><tr><td  style="background-color:hsla(225, 80%, 94%, 1);width:100px;"><b>b</b></td><td  style="width:100px;">3</td></tr></table>'


References:
http://epmoyer.github.io/ipy_table/
http://nbviewer.ipython.org/github/epmoyer/ipy_table/blob/master/ipy_table-Introduction.ipynb
http://nbviewer.ipython.org/github/epmoyer/ipy_table/blob/master/ipy_table-Reference.ipynb

1 Comment

Your dictList here is equivalent to dict.items(), is it not? I believe the for-loop and temporary variable are unnecessary.
4

A way to do it, but admittedly a hacky way, is to use json2html

from json2html import *
from IPython.display import HTML
HTML(json2html.convert(json = {'a':'2','b':'3'}))

but it needs a third party library

Comments

2

If you want later to externalise somewhere the HTML template and keep the control on it, it could be a good idea to use a templating engine. For this purpose you can use Jinja (it's pretty much a standard in Python).

from jinja2 import Template
from IPython.display import HTML

d = {'a': 2, 'b': 3}

# content of the template that can be externalised
template_content = """
<table>
{% for key, value in data.items() %}
   <tr>
        <th> {{ key }} </th>
        <td> {{ value }} </td>
   </tr>
{% endfor %}
</table>"""

template = Template(template_content)

# template rendering embedded in the HTML representation
HTML(template.render(data=d))

enter image description here

Comments

1

IPython Notebook will use the method _repr_html_ to render HTML output of any object having a _repr_html_ method

import markdown
class YourClass(str):
    def _repr_html_(self):
        return markdown.markdown(self)
d = {'a': 2, 'b': 3}
rows = ["| %s | %s |" % (key, value) for key, value in d.items()]
table = "------\n%s\n------\n" % ('\n'.join(rows))
YourClass(table)

This solution needs the third part library markdown

3 Comments

That results in an ImportError: No module named markdown error
Ok my fault! I had a typo when looking for markdown at pypi.
The output didn't look helpful for this example - all on one line. What did it look like for you?
1

One way to do it...

from IPython.display import HTML, display


def print_dict_as_html_table(some_dict):
    
        # create a list that will hold the html content  
        # initialise with the <table> tag
        html_list = ["<table>"]
        
        #iterate through the dictionary, appending row and element tags to the list
        for key in some_dict.keys():
            html_list.append("<tr>")
            html_list.append("<td>{0}</td>".format(key))
            html_list.append("<td>{0}</td>".format(some_dict[key]))
            html_list.append("</tr>")
            
        # add the final </table> tag to the list
        html_list.append("</table>")
        
        # create a string from the list
        html_string = ' '.join([str(elem) for elem in html_list])

        #display the html 
        display(HTML(html_string))



dict1 = {1: 2, "foo": "bar", "cat": "dog"}

print_dict_as_html_table(dict1)

Image of the output:

Output appearance in a notebook

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.