Python 字典作为 html table 在 ipython 笔记本中

Python dictionary as html table in ipython notebook

是否有任何(现有的)方法可以在 ipython 笔记本中将 python 字典显示为 html table。假设我有一本字典

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

然后我运行

magic_ipython_function(d)

给我类似

的东西

您可能正在寻找类似 ipy_table 的内容。

另一种方法是对数据框使用 pandas,但这可能有点矫枉过正。

一种方法,但不可否认是一种 hacky 方法,是使用 json2html

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

但需要第三方库

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)

此方案需要第三方库markdown

我不会说 pandas 是矫枉过正,因为您可能会将 DataFrame 用作字典等。

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

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

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

您可以编写自定义函数来覆盖默认的 _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)

然后,像这样使用它:

DictTable(d)

输出将是:

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

想法来源:Blog post of ListTable

工作代码: 在 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()

出[1]:


得到生成的html:

在[2]中:

render()._repr_html_()

出[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>'


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

如果您以后想在某个地方外部化 HTML 模板并保留对它的控制,使用 模板引擎 可能是个好主意。为此,您可以使用 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))

一种方法...

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)

输出图像: