是否有任何(现有)方法可以在 ipython 笔记本中将 python 字典显示为 html 表。假设我有一本字典
d = {'a': 2, 'b': 3}
然后我跑
magic_ipython_function(d)
给我类似的东西
最佳答案
您可以编写自定义函数来覆盖默认的 _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。
关于Python 字典作为 ipython 笔记本中的 html 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30523735/