conversion.py 2.8 KB

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