Generate HTML Table from Python Dictionary

Error_Coding picture Error_Coding · Apr 5, 2014 · Viewed 24.8k times · Source

How would I convert below dictionary into html table

  {'Retry': ['30', '12', '12'] 'Station MAC': ['aabbccddeea', 'ffgghhiijj', 'kkllmmnnoo'] Download': ['70.', '99', '90'] }

Html table format I am trying to achieve is

Retry       MAC         Download
  30      aabbccddee        70
  12      ffgghhiijj        99
  12      kkllmmnnoo        90

I have written css for table with border and everything, but data is not getting filled correctly. I am trying this with web2py. But Finding difficult to write logic to print above dictionary in table format.

Thanks !

Answer

Anthony picture Anthony · Apr 5, 2014

You can make it a little easier by using the web2py TABLE and TR helpers:

In the controller:

def myfunc():
    d = {'Retry': ['30', '12', '12'],
         'Station MAC': ['aabbccddeea', 'ffgghhiijj', 'kkllmmnnoo'],
         'Download': ['70.', '99', '90']}
    colnames = ['Retry', 'Station MAC', 'Download']
    rows = zip(*[d[c] for c in colnames])
    return dict(rows=rows, colnames=colnames)

And in the view:

{{=TABLE(THEAD(TR([TH(c) for c in colnames])),
         [TR(row) for row in rows]))}}