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

gre*_*ole 17 python ipython-notebook

是否有任何(现有的)方法在ipython笔记本中将python字典显示为html表.说我有一本字典

d = {'a': 2, 'b': 3}
Run Code Online (Sandbox Code Playgroud)

然后我跑了

magic_ipython_function(d)
Run Code Online (Sandbox Code Playgroud)

给我一些类似的东西

在此输入图像描述

Ami*_*ory 12

你可能正在寻找像ipy_table这样的东西.

另一种方法是将pandas用于数据帧,但这可能是一种过度杀伤力.


Gur*_*gde 12

您可以编写自定义函数来覆盖默认_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)
Run Code Online (Sandbox Code Playgroud)

然后,使用它像:

DictTable(d)
Run Code Online (Sandbox Code Playgroud)

输出将是: DictTable的示例输出

如果您要处理更大的数据(数千项),请考虑使用大熊猫.

想法来源:ListTable的博客文章


jrj*_*rjc 5

我不会说 Pandas 是一种矫枉过正,因为您可能会使用 DataFrame 作为 dict 等等。

无论如何,你可以这样做:

pd.DataFrame.from_dict(d, orient="index")
Run Code Online (Sandbox Code Playgroud)

或者

pd.DataFrame(d.values(), index=d.keys())
Run Code Online (Sandbox Code Playgroud)


jes*_*unk 5

工作代码:在Python 2.7.9和Python 3.3.5中测试

在[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()
Run Code Online (Sandbox Code Playgroud)

出[1]:

表截图


获取生成的html:

在[2]中:

render()._repr_html_()
Run Code Online (Sandbox Code Playgroud)

出[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>'
Run Code Online (Sandbox Code Playgroud)


参考文献:
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