简体   繁体   English

Python字典作为ipython笔记本中的html表

[英]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. 有没有(现有的)方法在ipython笔记本中将python字典显示为html表。 Say I have a dictionary 说我有一本字典

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

then i run 然后我跑了

magic_ipython_function(d)

to give me something like 给我一些类似的东西

在此输入图像描述

You're probably looking for something like ipy_table . 你可能正在寻找像ipy_table这样的东西

A different way would be to use pandas for a dataframe, but that might be an overkill. 另一种方法是将pandas用于数据帧,但这可能是一种过度杀伤力。

You can write a custom function to override the default _repr_html_ function. 您可以编写自定义函数来覆盖默认的_repr_html_函数。

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: 输出将是: DictTable的示例输出

If you are going to handle much bigger data (thousands of items), consider going with pandas. 如果您要处理更大的数据(数千项),请考虑使用熊猫。

Source of idea: Blog post of ListTable 想法来源: ListTable的博客文章

Working Code: Tested in Python 2.7.9 and Python 3.3.5 工作代码:在Python 2.7.9和Python 3.3.5中测试

In [1]: 在[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]: 出[1]:

table screenshot


Get the generated html: 获取生成的html:

In [2]: 在[2]中:

render()._repr_html_()

Out [2]: 出[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://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-Introduction.ipynb
http://nbviewer.ipython.org/github/epmoyer/ipy_table/blob/master/ipy_table-Reference.ipynb http://nbviewer.ipython.org/github/epmoyer/ipy_table/blob/master/ipy_table-Reference.ipynb

A way to do it, but admittedly a hacky way, is to use json2html 一种方法,但无可否认,这是一种hacky方式,是使用json2html

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

but it needs a third party library 但它需要第三方库

I wouldn't say pandas is an overkill, as you might use the DataFrame as a dict, among other things. 我不会说熊猫是一种矫枉过正,因为你可能会使用DataFrame作为dict等等。

Anyway, you can do: 无论如何,你可以这样做:

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

or 要么

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

IPython Notebook will use the method _repr_html_ to render HTML output of any object having a _repr_html_ method IPython Notebook将使用_repr_html_方法呈现具有_repr_html_方法的任何对象的HTML输出

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 该解决方案需要第三部分库markdown

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 . 如果您希望以后在某个地方外部化HTML模板并对其进行控制,那么使用模板引擎可能是个好主意。 For this purpose you can use Jinja (it's pretty much a standard in Python). 为此,您可以使用Jinja (它几乎是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))

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM