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

标签 python ipython-notebook

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

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

然后我跑

magic_ipython_function(d)

给我类似的东西

enter image description here

最佳答案

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

输出将是: Sample Output of DictTable

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

创意来源:Blog post of ListTable

关于Python 字典作为 ipython 笔记本中的 html 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30523735/

相关文章:

python - Pandas - 以正确的方式连接两个不同结构的 JSON

python - 将 Pandas 多索引数据框转换为嵌套字典

python - 将 jupyter notebook 转为 python 脚本的最佳实践

python - 系统退出 : 2 error when calling parse_args() in iPython Notebook

ipython-notebook - 将IPython笔记本转换为PDF时如何获得横向?

python - 保存/加载字典,同时保留键的数据类型

Python:元组中的列表

Python - 如何在 subprocess.Popen 中从 PIPE 进行非阻塞读取?

Pandas df.head() 错误

python - 在 iPython notebook 中动态更新绘图