Generate HTML Table from Python Dictionary
Asked Answered
F

4

6

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 !

Fifty answered 4/4, 2014 at 22:27 Comment(0)
L
5

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]))}}
Lobotomy answered 5/4, 2014 at 0:34 Comment(4)
This is actually creating an additional row after element.Fifty
Thank You ! This is Great ! But only thing is additional rowFifty
Too bad web2py isn't available for python 3Lexical
Not sure why you would post that comment here in particular, but Python 3 support is coming very soon.Lobotomy
M
4

Using a dict won't maintain the order of your columns but if you are ok with that then this example will work

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

html = '<table><tr><th>' + '</th><th>'.join(data.keys()) + '</th></tr>'

for row in zip(*data.values()):
    html += '<tr><td>' + '</td><td>'.join(row) + '</td></tr>'

html += '</table>'

print html
Monnet answered 4/4, 2014 at 22:47 Comment(1)
Or keep the order by using data=OrderedDict()Addlebrained
S
3

Something like

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

keys = d.keys()
length = len(d[keys[0]])

items = ['<table style="width:300px">', '<tr>']
for k in keys:
    items.append('<td>%s</td>' % k)
items.append('</tr>')

for i in range(length):
    items.append('<tr>')
    for k in keys:
        items.append('<td>%s</td>' % d[k][i])
    items.append('</tr>')

items.append('</table>')

print '\n'.join(items)
Squirmy answered 4/4, 2014 at 22:40 Comment(0)
F
1

Had quite a thorough search regarding this issue. By far the best solution I found was the prettytable package courtesy of Google. I'd give an example, but the ones in the link are comprehensive.

Forcer answered 8/4, 2015 at 17:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.