Python dictionary as html table in ipython notebook

jupyter display, html
jupyter notebook table style
table beautifier jupyter notebook
python dict to table
ipython display(markdown)
ipython core display(html object)
dictionary jupyter notebook
ipython display(javascript)

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

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

This uses Pygments to highlight the code for HTML and Latex output. Parameters e.g. to embed a link that was generated in the IPython notebook as my/data.txt. you would do: metadata (dict) – Specify extra metadata to attach to the json display object. Examples objs (tuple of objects) – The Python objects to display​. Python dictionary as html table in ipython notebook. 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 . Solutions/Answers: Solution 1:

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.

is there (existing) way display python dictionary html table in ipython notebook. have dictionary d = {'a': 2, 'b': 3}. then run magic_ipython_function(d). to give me. 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

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

Data Wrangling with Pandas, NumPy, and IPython Wes McKinney is from a dict of equal-length lists or NumPy arrays: data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada​', 'Nevada', 5 Nevada 2003 3.2 If you are using the Jupyter notebook, pandas DataFrame objects will be displayed as a more browser-friendly HTML table. The IPython Notebook consists of two related components: An JSON based Notebook document format for recording and distributing Python code and rich text. A web-based user interface for authoring and running notebook documents. The Notebook can be used by starting the Notebook server with the command:

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

Not long ago, I needed to parse some HTML tables from our confluence website at work. easily manipulate, filter, convert and display in a jupyter notebook. 4, dict, mutable, Associative array (or dictionary) of key and v. IPython.display.set_matplotlib_close (close=True) ¶ Set whether the inline backend closes all figures automatically or not. By default, the inline backend used in the IPython Notebook will close all matplotlib figures automatically after each cell is run. This means that plots in different cells won’t interfere.

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())

This allows for easily formatting the way tables are displayed. "language": "​python", black;border: 1px solid black;\">1</td><td style=\"color: black;border: 1px solid black;\">6</td><td "This basically stores a dictionary of CSS properties and values, and a function for how to format the data in cells. You can also drag and drop .ipynb notebooks and standard .py Python source code files into the notebook list area. When starting a notebook server from the command line, you can also open a particular notebook directly, bypassing the dashboard, with ipython notebook my_notebook.ipynb. The .ipynb extension is assumed if no extension is given.

Table 6-1 gives an overview of the most important IPython commands. (O'Reilly​, 2013) and at http://ipython.readthedocs.io/en/ stable/interactive/magics.html. The notebooks use IPython to execute Python code from a web browser, allow The name is used as the key of a dictionary that Python uses internally to find the​  The IPython Notebook is now known as the Jupyter Notebook. It is an interactive computational environment, in which you can combine code execution, rich text, mathematics, plots and rich media. For more details on the Jupyter Notebook, please see the Jupyter website.

from IPython.display import SVG SVG(filename='img/python-logo.svg') makes use of this capability to allow DataFrames to be represented as HTML tables. IPython Tips & Tricks. Embed IPython in your programs; Run doctests; Use IPython to present interactive demos; Suppress output; Lightweight ‘version control’ IPython reference. Command-line usage; Interactive use; IPython as your default Python environment; Embedding IPython; Using the Python debugger (pdb) Pasting of code starting with

Render a DataFrame as an HTML table. Parameters formatterslist, tuple or dict of one-param. functions, optional Whether the generated HTML is for IPython Notebook. borderint A css id is included in the opening <table> tag if specified. The following are code examples for showing how to use IPython.display.HTML().They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Comments
  • Have a look at IPython rich display system: nbviewer.ipython.org/github/ipython/ipython/blob/1.x/examples/…
  • Small adjustment for python 3: use for key, value in iter(self.items()): for the loop
  • Looks interesting, especially the possibility to style the tables.
  • Your dictList here is equivalent to dict.items(), is it not? I believe the for-loop and temporary variable are unnecessary.
  • 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?