conversion.py 2.5 KB

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