I have dictionary and would like to produce html page where will be drawn simple html table with keys and values. How it can be done from python code?
-
2Umm... print HTML in your Python code, maybe?Michael Myers– Michael Myers ♦2009-12-23 16:07:33 +00:00Commented Dec 23, 2009 at 16:07
-
1You'll need to provide more information. How are you outputting this HTML; are you using a template library like Genshi? How are you producing a table from a dictionary? Is each item in the dict a list of values for that column?DNS– DNS2009-12-23 16:08:09 +00:00Commented Dec 23, 2009 at 16:08
-
I don't use any template libraries and if you can advice something to have output then it would be good. Html table is simple. Two columns where first are the keys and second their corresponding values.yart– yart2009-12-23 16:11:57 +00:00Commented Dec 23, 2009 at 16:11
Add a comment
|
5 Answers
output = "<html><body><table>"
for key in your_dict:
output += "<tr><td>%s</td><td>%s</td></tr>" % (key, your_dict[key])
output += "</table></body></html>
print output
4 Comments
jbochi
maybe you meant 'for key, value in your_dict:' ;-)
bobince
Remember to HTML-escape any text you concatenate into HTML, or you'll have bugs and cross-site-scripting security holes.
rui
Fixed the value issue, thanks jbochi. Regarding HTML escaping I could have added cgi.escape(...) but I'll leave it simple.
yart
Thank you rui. Formatting html strings is enough for simple html table.
Along with the numerous template engines, you might consider using Python's built in Template. It will give you basic templating functionality without needing to learn (or choose) a template library.