Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dictionary as html table in ipython notebook

Tags:

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

like image 371
greole Avatar asked May 29 '15 07:05

greole


1 Answers

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

like image 95
Gurupad Hegde Avatar answered Oct 14 '22 09:10

Gurupad Hegde