是否有任何(現有)的方式在ipython筆記本中將Python字典顯示爲html表格。說我有一本字典Python字典作爲ipython筆記本中的html表格
d = {'a': 2, 'b': 3}
然後我運行
magic_ipython_function(d)
給我像
是否有任何(現有)的方式在ipython筆記本中將Python字典顯示爲html表格。說我有一本字典Python字典作爲ipython筆記本中的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)
輸出將是:
如果你要處理更大的數據(上千項),考慮與熊貓去。
python 3的小調整:在iter(self.items())中使用'key,value':'for循環 –
一個辦法做到這一點,但無可否認的一個哈克的方式,就是用json2html
from json2html import *
from IPython.display import HTML
HTML(json2html.convert(json = {'a':'2','b':'3'}))
,但它需要一個第三方庫
IPython的筆記本電腦將使用的方法_repr_html_
渲染HTML具有_repr_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
我不會說熊貓是一個矯枉過正的問題,因爲您可能會使用DataFrame作爲字典等等。
無論如何,你可以這樣做:
pd.DataFrame.from_dict(d, orient="index")
或
pd.DataFrame(d.values(), index=d.keys())
工作代碼:測試在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
您的'dictList'等價於'dict.items()',不是嗎?我相信for循環和臨時變量是不必要的。 – keturn
查看IPython豐富的顯示系統:http://nbviewer.ipython.org/github/ipython/ipython/blob/1.x/examples/notebooks/Part%205%20-%20Rich%20Display%20System.ipynb #HTML – fouronnes