# -*- coding: utf-8 -*- """ Created on Sun Jun 23 13:40:19 2013 @author: pietro """ dcont = """ {key} {value} """ def dict2html(dic, keys=None, border='', kfmt='%s', kdec='', kfun=None, vfmt='%s', vdec='', vfun=None): """Return a html repr of a dictionary. :param dict dic: dictionary or object with `keys` and `items` methods :param keys: iterable objectwith only the keys that we want to display :param str border: could be: "0", "1", etc. :param str kfmt: string to format the key string (i.e. "%r", etc.) :param str kdec: string to decorate the key (i.e. "b", "i", etc.) :param str vfmt: string to format the value string (i.e. "%r", etc.) :param str vdec: string to decorate the value (i.e. "b", "i", etc.) >>> dic = {'key 0': 0, 'key 1': 1} >>> print (dict2html(dic))
key 0 0
key 1 1
>>> print (dict2html(dic, border="1"))
key 0 0
key 1 1
>>> print (dict2html(dic, kdec='b', vfmt='%05d', vdec='i'))
key 0 00000
key 1 00001
>>> dic = {'key 0': (2, 3), 'key 1': (10, 5)} >>> print (dict2html(dic, kdec='b', vdec='i', ... vfun=lambda x: "%d%.1f" % x))
key 0 23.0
key 1 105.0
""" def fun(x): return x keys = keys if keys else sorted(dic.keys()) header = "" % border if border else "
" kd = "<%s>%s" % (kdec, kfmt, kdec) if kdec else kfmt vd = "<%s>%s" % (vdec, vfmt, vdec) if vdec else vfmt kfun = kfun if kfun else fun vfun = vfun if vfun else fun content = [dcont.format(key=kd % kfun(k), value=vd % vfun(dic[k])) for k in keys] return '\n'.join([header, ] + content + ['
', ])