conversion.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Sun Jun 23 13:40:19 2013
  4. @author: pietro
  5. """
  6. dcont = """ <tr>
  7. <td>{key}</td>
  8. <td>{value}</td>
  9. </tr>"""
  10. def dict2html(dic, keys=None, border='',
  11. kfmt='%s', kdec='', kfun=None,
  12. vfmt='%s', vdec='', vfun=None):
  13. """Return a html repr of a dictionary.
  14. :param dict dic: dictionary or object with `keys` and `items` methods
  15. :param keys: iterable objectwith only the keys that we want to display
  16. :param str border: could be: "0", "1", etc.
  17. :param str kfmt: string to format the key string (i.e. "%r", etc.)
  18. :param str kdec: string to decorate the key (i.e. "b", "i", etc.)
  19. :param str vfmt: string to format the value string (i.e. "%r", etc.)
  20. :param str vdec: string to decorate the value (i.e. "b", "i", etc.)
  21. >>> dic = {'key 0': 0, 'key 1': 1}
  22. >>> print dict2html(dic)
  23. <table>
  24. <tr>
  25. <td>key 0</td>
  26. <td>0</td>
  27. </tr>
  28. <tr>
  29. <td>key 1</td>
  30. <td>1</td>
  31. </tr>
  32. </table>
  33. >>> print dict2html(dic, border="1")
  34. <table border='1'>
  35. <tr>
  36. <td>key 0</td>
  37. <td>0</td>
  38. </tr>
  39. <tr>
  40. <td>key 1</td>
  41. <td>1</td>
  42. </tr>
  43. </table>
  44. >>> print dict2html(dic, kdec='b', vfmt='%05d', vdec='i')
  45. <table>
  46. <tr>
  47. <td><b>key 0</b></td>
  48. <td><i>00000</i></td>
  49. </tr>
  50. <tr>
  51. <td><b>key 1</b></td>
  52. <td><i>00001</i></td>
  53. </tr>
  54. </table>
  55. >>> dic = {'key 0': (2, 3), 'key 1': (10, 5)}
  56. >>> print dict2html(dic, kdec='b', vdec='i',
  57. ... vfun=lambda x: "%d<sup>%.1f</sup>" % x)
  58. <table>
  59. <tr>
  60. <td><b>key 0</b></td>
  61. <td><i>2<sup>3.0</sup></i></td>
  62. </tr>
  63. <tr>
  64. <td><b>key 1</b></td>
  65. <td><i>10<sup>5.0</sup></i></td>
  66. </tr>
  67. </table>
  68. """
  69. def fun(x):
  70. return x
  71. keys = keys if keys else sorted(dic.keys())
  72. header = "<table border=%r>" % border if border else "<table>"
  73. kd = "<%s>%s</%s>" % (kdec, kfmt, kdec) if kdec else kfmt
  74. vd = "<%s>%s</%s>" % (vdec, vfmt, vdec) if vdec else vfmt
  75. kfun = kfun if kfun else fun
  76. vfun = vfun if vfun else fun
  77. content = [dcont.format(key=kd % kfun(k), value=vd % vfun(dic[k]))
  78. for k in keys]
  79. return '\n'.join([header, ] + content + ['</table>', ])