conversion.py 2.5 KB

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