Reputation: 4771
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
Upvotes: 24
Views: 22405
Reputation: 6284
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:
Upvotes: 1
Reputation: 21898
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))
Upvotes: 2
Reputation: 2155
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:
If you are going to handle much bigger data (thousands of items), consider going with pandas.
Source of idea: Blog post of ListTable
Upvotes: 15
Reputation: 2472
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]:
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
Upvotes: 6
Reputation: 21873
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())
Upvotes: 11
Reputation: 7303
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
Upvotes: 1
Reputation: 4771
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
Upvotes: 4
Reputation: 76317
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.
Upvotes: 13