how to write a html to automatically display the dictionary?

Denis McMahon denismfmcmahon at gmail.com
Tue Sep 23 22:53:42 CEST 2014


On Tue, 23 Sep 2014 17:34:53 +0000, John Gordon wrote:

> In <mailman.14262.1411481932.18130.python-list at python.org> luofeiyu
> <elearn2014 at gmail.com> writes:
> 
>> x={'f1':1,'f2':2,'f3':3}
>> how can i create the following html file automatically with python to
>> display x ?
> 
> You might want to use something other than a dictionary, as the order
> isn't guaranteed.

Assuming you want them in order of the key field:

from string import *

x={'f1':1,'f2':2,'f3':3}
y = [ (a,x[a]) for a in x.keys() ]
y.sort( cmp=lambda a,b: cmp(a[0],b[0]) )
table = ( "<table>\n" +
          "\n".join(["<tr>\n" +
                     "\n".join(["<td>{}</td>".format(z[i]) for z in y]) +
                     "\n</tr>" for i in range(len(y[0]))]) +
          "\n</table>" )
print table

-- 
Denis McMahon, denismfmcmahon at gmail.com



More information about the Python-list mailing list