1
# -*- coding: utf-8 -*-
3
Created on Sun Jun 23 13:40:19 2013
15
def dict2html(dic, keys=None, border='',
16
kfmt='%s', kdec='', kfun=None,
17
vfmt='%s', vdec='', vfun=None):
18
"""Return a html repr of a dictionary.
20
:param dict dic: dictionary or object with `keys` and `items` methods
21
:param keys: iterable objectwith only the keys that we want to display
22
:param str border: could be: "0", "1", etc.
23
:param str kfmt: string to format the key string (i.e. "%r", etc.)
24
:param str kdec: string to decorate the key (i.e. "b", "i", etc.)
25
:param str vfmt: string to format the value string (i.e. "%r", etc.)
26
:param str vdec: string to decorate the value (i.e. "b", "i", etc.)
28
>>> dic = {'key 0': 0, 'key 1': 1}
29
>>> print dict2html(dic)
40
>>> print dict2html(dic, border="1")
51
>>> print dict2html(dic, kdec='b', vfmt='%05d', vdec='i')
62
>>> dic = {'key 0': (2, 3), 'key 1': (10, 5)}
63
>>> print dict2html(dic, kdec='b', vdec='i',
64
... vfun=lambda x: "%d<sup>%.1f</sup>" % x)
68
<td><i>2<sup>3.0</sup></i></td>
72
<td><i>10<sup>5.0</sup></i></td>
79
keys = keys if keys else sorted(dic.keys())
80
header = "<table border=%r>" % border if border else "<table>"
81
kd = "<%s>%s</%s>" % (kdec, kfmt, kdec) if kdec else kfmt
82
vd = "<%s>%s</%s>" % (vdec, vfmt, vdec) if vdec else vfmt
83
kfun = kfun if kfun else fun
84
vfun = vfun if vfun else fun
85
content = [dcont.format(key=kd % kfun(k), value=vd % vfun(dic[k]))
87
return '\n'.join([header, ] + content + ['</table>', ])